How to Detect and Run JavaScript When Bootstrap Media Query Breakpoints Change

  • Updated on
  • read
  • Add to Flipboard Magazine.

How to Run JavaScript When Bootstrap 3 Breakpoints Change

Update: I created a small jQuery plugin that adds media query detection for Bootstrap 3 and 4 projects. You can learn more about IfBreakpoint.js here.

Have you ever wanted to trigger some javascript at a certain media query value? Relying on document.width() has problems because it includes browser scrollbars. A simpler and more accurate solution is to rely on CSS to trigger the javascript.

Bootstrap 3 has some nice responsive visibility classes that are triggered at the various breakpoints. What we will do is add a series of span tags with these classes and check when they are set to display block. Since they are inline by default, we will know media query breakpoint fired when the CSS display property changes.

View Demo

Adds some invisible span elements to trigger Bootstrap CSS media queries

Write a function to check if an element is set to display block

Set some variables to use with the if conditional statements below

Now write a series of if condition statements to check if they are true/false

Below is the completed script

Works cited
http://stackoverflow.com/questions/20181219/twitter-bootstrap-how-to-detect-when-media-queries-starts
http://jsfiddle.net/ejVvu/1/




Written by: Jacob Lett
Category: Tutorials
Tags: ,

Leave a comment

Related Posts

Blog Home

Categories

Topics