user2537485 user2537485 - 1 month ago 5
Javascript Question

I can't seem to get my dropdown code to function properly

I am trying to create a drop down menu that when the drop down button is clicked it shows the sub menu. When I click anywhere else though it should hide the sub menu.

Here is my code:

function initMainNavigation( container ) {

container.find( '.dropdown-toggle' ).click(function(e){
var dropdown = $( this );
e.preventDefault();
dropdown.next( '.children, .sub-menu' ).toggleClass( 'toggled-on' );
});

$("body").click(function(){
var dropdown = container.find( '.dropdown-toggle' );
dropdown.next( '.children, .sub-menu' ).removeClass('toggled-on');
});

}
initMainNavigation( $( '.main-navigation' ) );


But when I click the dropdown toggle the sub menu won't show. When I debugged it in firebug, the $("body").click() event is triggered as well. I am guessing it's because the '.main-navigation' is inside the "body".

I know that it works if I remove $("body").click(). However I can't click else where to hide the sub menu.

Answer

Your body click event bubbles to the .dropdown-toggle container so when you click .dropdown-toggle you trigger both events

function initMainNavigation( container ) {

    container.find( '.dropdown-toggle' ).click(function(e){
        var dropdown = $( this );
        e.preventDefault();
        dropdown.next( '.children, .sub-menu' ).toggleClass( 'toggled-on' );
     });

    $("body").click(function(e){
        var dropdown = container.find( '.dropdown-toggle' );
        if(!$(e.target).closest('.dropdown-toggle').length) {//trigger the  toggle only if the element is not .dropdown-toggle or a child of it
        dropdown.next( '.children, .sub-menu' ).removeClass('toggled-on');
         }
    });

}
initMainNavigation( $( '.main-navigation' ) );