ok1ha ok1ha - 1 month ago 7
jQuery Question

Menu toggle not working when using not (this)

I'm building a basic dropdown menu, and when you click a menu item, I want make sure any open dropdowns close first.

Using not(this) on line two, allows toggleClass to toggle on, but off.

What am I missing?

$( '.nav-dropdown' ).click( function(){
$( '.nav-dropdown-content' ).not( this ).addClass( 'hide' );
$( '.nav-dropdown-content', this ).toggleClass( 'hide' );
});


Here's the HTML

<div class="nav_wrapper">
<ul>
<li class="nav-dropdown">
Menu Item 1 <span>&dtrif;</span>
<div class="nav-dropdown-content">
<a href="#">Sub Menu 1</a>
<a href="#">Sub Menu 2</a>
</div>
</li>
<li class="nav-dropdown">
Menu Item 2 <span>&dtrif;</span>
<div class="nav-dropdown-content">
<a href="#">Sub Menu 3</a>
<a href="#">Sub Menu 4</a>
</div>
</li>
</ul>
</div>

Answer

Try the following

 $( '.nav-dropdown' ).click( function(){
     var $content = $( '.nav-dropdown-content', this ).toggleClass( 'hide' );
     // exclude the current content instance
     $( '.nav-dropdown-content' ).not( $content ).addClass( 'hide' );      
});

this is the $( '.nav-dropdown' ) element, so you can't use it as not() for $( '.nav-dropdown-content' )

Comments