1
\$\begingroup\$

In a bigger project of mine I'm using angular to create a dropdown menu dynamically and then toggling a dropdown menu for some of the menu items. This is why I got a function that toggles the dropdown menus for only the items that should actually have one. However, I feel like I should try to DRY this out a bit since I'll be repeating the same function even more than what I've done so far. How can I improve this code? Should I create a self invoking function or something similar?

Here's the functions (they're part of a controller object that I left out):

    init: function() {

        menuController.toggleDropDown('msg');
        menuController.toggleDropDown('mypages');
        menuController.toggleDropDown('tools');
        menuController.toggleDropDown('administration');
        menuController.toggleDropDown('contactinfo');
        menuController.toggleDropDown('utbildning');
        menuController.toggleDropDown('surveys');
        menuController.toggleDropDown('help');
    },
    toggleDropDown: function (id) {

        $('#main-menu' + ' #' + id + '').hover(function() {
            $('#' + id + ' ul').stop().slideToggle();
        });
    }
\$\endgroup\$
1
\$\begingroup\$

I think you can use html attribute to group it.

eg.

<div data-toggle="dropdown"> or
<a data-toggle="dropdown"> or whatever

and then

$('#main-menu [data-toggle="dropdown"]').hover(function(e) {
    $(e.currentTarget).find('ul').stop().slideToggle();
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.