Oliver Nassar

Twitter Bootstrap: Accordion/Collapse Event Bubbling with the Modal Plugin

August 10, 2012

I'm hopeful this one will help someone save some time, especially considering the usage of jQuery and Twitter Bootstrap.

While I'm a MooTools developer at heart, I can't help but appreciate the plugins that Twitter has available for use with bootstrap.

I was running into an issue when having an Accordion/Collapse plugin within a Modal plugin instance.

Specifically, the hidden event was firing whenever an accordion was collapse. In my case, I'm using live events for both the modal closing as well as the accordion interactions, but I'm not sure if that's the reason for my edge-case.

So whenever an accordion was collapse within a modal, it would fire off the modal's hidden event, which in my case would remove it from the DOM. Definitely not what I wanted.

It took me a while to figure it out, but the result is that I have to manually create the accordion interactions (using the plugin, that is), and define the hidden event on the accordions themselves. I need to tell them not to bubble up the DOM to fire off the modal's events. Here's what the code for that looks like:

$(document).on(
    'click',
    'a.accordion-toggle',
    function(event) {
        event.preventDefault();
        var href = $(this),
            parent = $(this).parent().parent(),
            body = parent.find('.accordion-body');
        body.collapse('toggle');
        body.on('hidden', function(event) {
            event.stopPropagation();
        });
    }
);

This did it for me. While it's not as elegant as using the data-toggle="collapse" attribute on an anchor to have all the magic happen automatically, it does address this edge-case which had unexpected interactions going on.

Hope that helps :)