Reputation: 157
I'm trying to create links that open their submenus on click. At the moment, the script just opens all the submenus and not the ones assigned to that specific link.
HTML
<nav>
<ul>
<li>
<a class="menu">Category A</a>
<ul class="submenu">
<li><a href="#">Item A</a></li>
<li><a href="#">Item B</a></li>
</ul>
</li>
<li>
<a class="menu">Category B</a>
<ul class="submenu">
<li><a href="#">Item C</a></li>
<li><a href="#">Item D</a></li>
</ul>
</li>
</ul>
</nav>
jQuery
$("nav ul li").click(function() {
var submenu = $(this).find('.submenu');
$('.submenu').not(submenu).fadeToggle().removeClass('opened');
submenu.addClass('opened').fadeToggle();
});
Here is my jsfiddle
If Category A is clicked, I want it to show only the Item A and Item B. (At the moment it displays all items from all categories) Then if Category B is clicked, I want it to hide the Category A and only show the currently open category.
Upvotes: 0
Views: 523
Reputation: 952
<nav>
<ul class="container">
<li>
<a class="menu">Category A</a>
<ul class="submenu">
<li><a href="#">Item A</a></li>
<li><a href="#">Item B</a></li>
</ul>
</li>
<!-- ... -->
</ul>
</nav>
$(".container .menu").click(function(e) {
e.preventDefault();
var $this = $(this);
var $menu = $this.parent();
var $container = $this.closest("ul.container");
$container.find('ul').removeClass('opened').fadeOut('fast', function() {
var $submenu = $menu.find('.submenu');
$submenu.fadeIn('fast').addClass('opened');
});
});
Keep in mind this could me done completely with CSS without any javascript
Upvotes: 0
Reputation: 4819
Fix:
Check for the anchor link's next sibling called .submenu
, then use that as a target to fade toggle the menu.
$("nav ul li a").click(function() {
var $submenu = $(this).next(".submenu").not(".opened");
$(".submenu.opened").fadeOut().removeClass("opened");
$submenu.fadeIn().addClass("opened");
});
Fiddle: http://jsfiddle.net/ov0Lapx4/1/
Upvotes: 0
Reputation: 37886
just do:
$(".menu").on('click', function() {
var submenu = $(this).next('.submenu');
if($('.thisul').find('.submenu') != $(this)){
$('.thisul').find('.submenu').fadeOut();
}
submenu.fadeToggle();
});
fiddle: http://jsfiddle.net/j44163w9/4/
and just add class
<nav>
<ul class="thisul">...
...
Upvotes: 1