I have some code that acts as an unordered list dropdown menu. It shows and hides well, but I am trying to work out how to make it add an active state to a parent element that is clicked if a nested child list exists. The code below seems to add the active state to any link that is clicked, whether it has children or not, but I don’t want that.
For example I want to add an active state to ‘In the News’ when it is clicked.
Please could someone help me?
My jQuery:
$('.infobox.lightbox.inlinks ul > li > ul')
.hide()
.click(function(e){
e.stopPropagation();
});
$('.infobox.lightbox.inlinks ul > li').toggle(function(){
$(this).find('ul').slideDown(),
$(this).addClass("expanded");
}, function(){
$(this).find('ul').slideUp(),
$(this).removeClass("expanded");
});
and my HTML:
<ul>
<li><a href="#">Press releases</a></li>
<li><a href="#">In the news</a>
<ul>
<li><a href="#">Photo galleries</a></li>
<li><a href="#">Videos</a></li>
<li><a href="#">Podcasts</a></li>
</ul>
</li>
<li><a href="#">Media Centre</a></li>
<li><a href="#">Fact Sheet</a></li>
<li><a href="#">Press Contacts</a></li>
</ul>
JQuery’s
.toggle()is used to hide/show elements, not “toggle” between functions.What you want to do something like this (although, there are plenty of other ways to go about it):
JAVASCRIPT:
DEMO: http://jsfiddle.net/dirtyd77/aZBXc/6/
Hope this helps!