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

  • 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

bootstrap 4 books

Bootstrap 4 Books & Templates

Learn More

Advertise Here

Written by: Jacob Lett - Jacob is an experienced website designer and developer who specializes in building HubSpot CMS themes. He helps Industrial companies optimize and leverage their website for awareness, lead generation, and branding.
Category: Tutorials
Tags: ,

Want to Get Email Updates?

Receive a monthly digest of new tutorials and resources.

bootstrap 4 books

Want a Bootstrap Reference Book?

Learn More

Advertise Here