I'm trying to change the 'active' class for the clicked list item but I'm missing something. Here is what my HTML and jquery look like:
HTML
<ul class="additional-menu">
<li class="active"><a href="link1"> Link1</a></li>
<li><a href="javascript:void(0)" id="link2">Link2</a></li>
<li><a href="javascript:void(0)" id="link3">Link3</a></li>
</ul>
jQuery
$("#link2").click(function(){
if ($(this).find('#additional-menu li').hasClass('active')) {
//console.log("Active class seen");
$(this).find('#additional-menu li').removeClass('active');
$(this).addClass('active');
}
});
Any idea what I'm missing? I'm not even detecting the active class at this point...
You could minimize your code to just
$('.additional-menu').on('click','li', function(){
$(this).addClass('active').siblings().removeClass('active');
});
Demo at http://jsfiddle.net/DvHBp/
There are many problems in the code
//from what i can understand you need to change the active class to the clicked li element not just the link2 element
$("#link2").click(function(){
// additional-menu is not an id it is a class and it is not a descendant of the li element
if ($(this).find('#additional-menu li').hasClass('active')) {
//console.log("Active class seen");
$(this).find('#additional-menu li').removeClass('active');
//if you are using a if statement then addClass should be outside the if block
$(this).addClass('active');
}
});
try
jQuery(function(){
var $lis = $('.additional-menu > li').click(function(){
$lis.removeClass('active');
$(this).addClass('active')
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With