Run
Run

Reputation: 57176

Bootstrap dropdown: events for the 'navbar-toggle'?

Do we have events for the navbar-toggle that appears when we are on the smaller screen?

For instance,

$('#myDropdown').on('shown.bs.navbar-toggle', function () {
  // do something…
});

$('#myDropdown').on('hide.bs.navbar-toggle', function () {
  // do something…
});

html,

<div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <!--<a class="navbar-brand" href="#">Home</a>-->
</div>

Otherwise, how can we detect if that navbar-toggle exists on the smaller screen?

Upvotes: 39

Views: 50742

Answers (3)

kashiraja
kashiraja

Reputation: 758

I couldn't get the show/shown or hide/hidden.bs.collapse events to be triggered. I tied the event to the #navbar element.

What did work for me was just using the resize event and then check if the navbar is visible:

Combining what @Patel, madhatter160 and @haxxxton suggested I was able to get it to work:

var navbar_visible = $("#navbar").is(":visible");

$(window).resize(function(){
  navbar_visible = $("#navbar").is(":visible");

  if (navbar_visible)
    $('#brand_name').text('Navbar is visible');
  else
    $('#brand_name').text('Navbar is not visible');
});

This is a pretty simple solution that doesn't need any special jQuery plugins to work. I wish it was possible to get this to work using the defined *.bs.collapse events though!

You can also try this our on jsFiddle.

Upvotes: 4

haxxxton
haxxxton

Reputation: 6442

Using jquery you can test if something is visible using .is(':visible'). http://api.jquery.com/visible-selector/

If you need its visibility to trigger something else you could look at implementing the jQuery Mutate plugin. This effectively monitors an element for a change in a property and then fires an event. http://www.jqui.net/jquery-projects/jquery-mutate-official/

Upvotes: -1

Eric Uldall
Eric Uldall

Reputation: 2391

The navbar-toggle methods emit the Collapse events:

Events

Bootstrap's collapse class exposes a few events for hooking into collapse functionality.

Event Type           Description
show.bs.collapse     This event fires immediately when the show instance method is called.
shown.bs.collapse    This event is fired when a collapse element has been made visible to     the user (will wait for CSS transitions to complete).
hide.bs.collapse     This event is fired immediately when the hide method has been called. 
hidden.bs.collapse   This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).

Example

$('#myCollapsible').on('hidden.bs.collapse', function () {
  // do something…
})

Docs: http://getbootstrap.com/javascript/#collapse

Upvotes: 73

Related Questions