shtev21
1/2/2014 - 2:41 PM

jQuery function to turn a list with sub-lists into a drop-down menu

jQuery function to turn a list with sub-lists into a drop-down menu

// Toggles the selected menu open/closed or closes any open menu before opening the required one
var subMenuOpen = function(clickTarget, parentEl, activeClass) {
    // Defining variables for all list items and sub menus as well as the required active ones
    $each_list       = clickTarget.parents(parentEl).find('li');
    $each_subMenu    = clickTarget.parents(parentEl).find('ul');
    $active_list     = clickTarget.parent('li');            
    $active_subMenu  = clickTarget.next('ul');
    
    // slide them all up first
    $each_subMenu.slideUp();
    
    // check if we should simply close the current menu or switch the active menu
    if ($active_list.hasClass(activeClass)) {
        $active_subMenu.slideUp(400, function(){
            $active_list.removeClass(activeClass);
        });
    } else {
        $each_list.removeClass(activeClass);                
        $active_list.addClass(activeClass);
        $active_subMenu.slideDown();
    }
};

// Closes all open menus
var subMenuClose = function(dropDownEl, activeClass){
    if ($(dropDownEl + ' li').hasClass(activeClass)) {
        $(dropDownEl + ' li ul').slideUp(400, function(){
            $(dropDownEl + ' li').removeClass(activeClass);
        });
    }
}

// Useage Example(s)

// Attatches a listener to the html that closes all dropdowns
$('html').on('click', function(){
    subMenuClose('.dropdown', 'active');
});

// Attatches a listener to anchors within '.dropdown' to instantiate the dropdown menu
$('.dropdown').on('click', 'a[href=""]', function(event){
    event.preventDefault(); // Prevents default click action if the target is an anchor
    event.stopPropagation(); // Prevents propogation of container events, such as a listener attatched to the html
    subMenuOpen($(this), '.dropdown', 'active');
})