javascripttwitter-bootstrap-3preventdefaultbootstrap-tabs

bootstrap tab click preventDefault not working


I am using bootstrap 3.3 and following the documents for tabs.

The simplest code given in the documentation is not working for me and I am unable to figure out why.

$('#mainTabs a').click(function (e) {
            e.preventDefault()
            console.log('Clicked');
        });

When I use

show.bs.tab

event, preventDefault works. But for somereason click doesn't. The console is printing 'clicked', but does not prevent the tab change.

Basically I am trying to intercept the tab change, show a modal and based on user input, show or not show the new tab.

Please help.


Solution

  • If e.preventDefault(); is not working you must use e.stopImmediatePropagation(); instead.

    For further information take a look at: What's the difference between event.stopPropagation and event.preventDefault?

    $("#mainTabs a").click(function(e) {
         e.stopImmediatePropagation();
    });
    

    If you've attached other event handlers to the link, you should look into e.stopPropagation() and e.stopImmediatePropagation() instead. Note that return false is equivalent to calling both event.preventDefault() and event.stopPropagation().

    EDIT ==========

    Use return false;.