Twitter Bootstrap 2 on collapse event

itsme picture itsme · May 17, 2012 · Viewed 21k times · Source

is there any way to catch when the collapse menu appears (or when collapse button is clicked by user) ?

i'm using standard bootstrap twitter framework and classes.

Answer

patspam picture patspam · Jan 25, 2014

In bootstrap 3.x, the four events you're looking for are:

show.bs.collapse
shown.bs.collapse
hide.bs.collapse
hidden.bs.collapse

They fire on the data-target DOM element, e.g. for the following mark-up:

<div role="navigation" class="navbar navbar-inverse">
  <div class="container">
    <div class="navbar-header">
      <button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="#" class="navbar-brand">Title</a>
    </div>
    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li id="item1"><a href="#item1">Menu Item 1</a></li>
      </ul>
    </div>
  </div>
</div>

You'd listen (in jQuery) via:

$('.navbar-collapse').on('shown.bs.collapse', function() { alert('shown'); });
$('.navbar-collapse').on('hidden.bs.collapse', function() { alert('hidden'); });