Reputation: 449
I'm trying to use Bootstrap 3 to make a responsive site. I am using their Dashboard example as a starting point.
The example has a breakpoint at 768px so that the top navigation bar goes from a "hamburger" menu button to a horizontal list of navigation items. I need to somehow react when that breakpoint is reached.
Based off this and this, I've tried to bind to the show/hide.bs.collapse events on the button element to no avail. Is there a way to bind to an event or somehow listen for when the breakpoint is reached?
I've set up a JSFiddle with the relevant parts (move the vertical slider to get the navbar to change). Here's the JavaScript I've tried:
$( ".navbar-toggle" ).on( "show.bs.collapse", function() {
alert( "hamburger show" );
} )
.on( "hide.bs.collapse", function() {
alert( "hamburger hide" );
} );
Upvotes: 6
Views: 3949
Reputation: 16383
Not related to breakpoints but related to Google keyword search: This worked for me on version 4.6.x of Bootstrap:
$(".navbar-collapse").on("show.bs.collapse", function () {
alert("hamburger show");
})
.on("hide.bs.collapse", function () {
alert("hamburger hide");
});
Upvotes: 3
Reputation: 1478
If you're just looking for a breakpoint, you can listen to resize
event and then do what you want to do with it.
$(window).on('resize', function() {
if($(window).width() == 768) {
//do something
console.log('Gotcha!');
}
});
This type of solution would work if user doesn't resize the window too quickly. Let me know if this works for you.
Upvotes: 0
Reputation: 537
Here's a neat solution I read about recently, that has worked really well for cases like this: https://www.fourfront.us/blog/jquery-window-width-and-media-queries
Basically you use jQuery to test for CSS rules that apply only to specific breakpoints. So for example, if you wanted to fire something at 768px when your hamburger is set to disappear, and you had some CSS written that uses media queries, you could do something like:
<h1>Example</h1>
h1 { font-size: 15px; }
@media only screen and (min-width: 768px) {
h1 { font-size: 30px; }
}
$(window).resize(function(){
var example = $('h1');
if (example.css('font-size') == '30px') {
alert('breakpoint');
}
});
Check out the fiddle: http://jsfiddle.net/hq651vjy/2/
Upvotes: 2