简体   繁体   中英

jQuery toggle div and toggle class

I've got a side navigation where a user can click on a link which then toggles a panel with options for that section. My problem with this at the moment is i need to be able to remove the class when a user clicks on the same link to hide the panel.

Right now the 'active' state is getting left on the link. It works fine when your clicking from one link to another, but id like it to also remove the 'active' state if someone wishes to hide the menu. The 'active' class is shown with the cyan highlight on the menu.

jsFiddle: http://jsfiddle.net/visualdecree/4A23Z/11/

jQuery:

$(".sn a").on('click',function(){

    var panID = $("#" + $(this).data('panel') );

    $("div[id*='sn-pan-']")
    .stop()
    .hide({slide:'toggle'}, 400);

    $(panID)
    .css({'left' : '100px','overflow':'visible'})
    .stop()
    .animate({width:'toggle'}, 400)
});

$('.sn').click(function(){
    $('ul.sidenav li').removeClass('active');                    
    $(this).stop(true,true).addClass("active");
});​

You can exclude the clicked item from the removeClass function, and toggle it instead like this

Changed from the jsFiddle provided below.

$('.sn').click(function(e) {
    $('ul.sidenav li').not(this).removeClass('active');
    $(this).stop(true, true).toggleClass("active");
});

You can check if the link has the active class and only add this class if it wasn't active yet:

$('.sn').click(function(){
   var isActive $(this).hasClass('active');
   $('ul.sidenav li').removeClass('active');

   $(this).stop(true,true);
   if(!isActive){
       $(this).addClass("active");
   }
}); 

working fiddle

Or just toggle the active class

 $('.sn').click(function(){
     $(this).toggleClass("active");
 });​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM