Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing active class for list element

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...

like image 892
Paul Avatar asked Dec 09 '22 11:12

Paul


2 Answers

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/

like image 53
Gabriele Petrioli Avatar answered Dec 10 '22 23:12

Gabriele Petrioli


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')    
    });
})
like image 21
Arun P Johny Avatar answered Dec 11 '22 01:12

Arun P Johny