When the documentation lists the available events, it’s just a promise that it will always raise each particular event at a particular time.
For example, hidden.bs.collapse
will be raised whenever:
a collapsed element has been hidden from the user.
Whether or not anybody’s listening to that event hasn’t yet come into play.
To leverage this, or any other, event, we can use jQuery’s .on()
method to attach listeners on particular html elements to see if they raise particular events.
Where we add the listener depends on where the event is going to be raised and when we want to capture it.
Simple Example:
Let’s say you have the basic HTML structure for an Accordion control:
<div class="panel-group" id="accordion">
<div class="panel panel-default" id="panel1"><!--...--></div>
<div class="panel panel-default" id="panel2"><!--...--></div>
<div class="panel panel-default" id="panel3"><!--...--></div>
</div>
In this case, each panel
class is going to raise this event. So if want to capture it there, we just use the jQuery class selector to attach listeners to all the .panel
objects like so:
$('.panel').on('hidden.bs.collapse', function (e) {
alert('Event fired on #' + e.currentTarget.id);
})
jsFiddle
But Wait There’s More…
In HTML, events will bubble from the innermost element to the outermost element if unhandled. So events raised for each individual .panel
, can also be handled by the entire .panel-group
(or even the body
element as they’ll eventually work their way up there).
In the bootstrap examples page, they are using the id selector for the entire panel-group
, which happens to be #myCollapsible
, but in our case is #accordion
. If we want to handle the event there, we can simply change the jQuery selector as follows:
$('#accordion').on('hidden.bs.collapse', function (e) {
alert('Event fired on #' + e.currentTarget.id);
})