Search code examples
jquerycsstwitter-bootstrapbootstrap-tabs

Collapse Bootstrap tabs - can't toggle .active tab class


I use (styled) Bootstrap tabs

I want to close Bootstrap tabs when clicking on it again.

It works partially, I can close the corresponding panel but when I want to toggle the 'active' class of the tab, script don't work.

My JS code :

$('[data-toggle=tab]').click(function(e){
    if($(this).parent().hasClass('active')){
        e.preventDefault();

        // toggle 'active' tab class (styling)
        $(this).parent().toggleClass('active');

        // toggle 'active' panel class (hide it)
        $($(this).attr("href")).toggleClass('active');
    }
})

All code (html, css, js) is visible here : https://jsfiddle.net/j9stkqf6/1/

If you comment :

$(this).parent().toggleClass('active');

the panel is hidden

I also tried step/step debug mode All works fine until end of JS function, all reappear (tab.active class and panel)

Can you help me close panel AND toggle tab 'active' class when clicking again on tab.

Thanks !


Solution

  • Finally I got it working :

    I had to add 'e.stopPropagation()' to my Javascript in addition to 'e.preventDefault()'

    'e.preventDefault()' stop the action from Bootstrap on that event (click on A link)

    'e.stopPropagation()' avoid other actions from Bootstrap (catch click on LI)

    cf. e.preventDefault() vs e.stopPropagation()

    $('[data-toggle=tab]').click(function(e){
        if($(this).parent().hasClass('active')){
    
        e.preventDefault();
        e.stopPropagation();
    
            $(this).parent().removeClass('active');
    
            $($(this).attr("href")).removeClass('active');
            $($(this).attr("href")).removeClass('in');
    
            $(this).attr("aria-expanded", false);
        }
    })
    

    You can see my working example here : https://jsfiddle.net/j9stkqf6/10/