Daniel Rubio Daniel Rubio - 4 months ago 9
jQuery Question

Toggle Menu individual List from enter key

Practicing some Jquery I have a simple un-ordered list that I want to expand when I press enter. but only the the one I press enter on not all of them. Possibly setting it up wrong. At the moment its expanding both items.

<nav>
<ul>
<li class="menu"><a href="#">Menu 1</a>
<ul class="subMenu">
<li>
<a href="">Sub Menu 1</a>
</li>
</ul>
</li>
<li class="menu"><a href="#">Menu 2</a>
<ul class="subMenu">
<li>
<a href="">Sub Menu 1</a>
</li>
<li>
<a href="">Sub Menu 2</a>
</li>
</ul>
</li>
</ul>




$('.menu').keydown(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
$('ul.subMenu').toggleClass('show');
}
});

Answer

Change $('ul.subMenu') to $(this).children('ul.subMenu'). This will search only for children of the current element (not all of them) that match the ul.subMenu selector (as desired).

See the jQuery children([selector]) function for more info.