Detecting CSS breakpoints in Javascript

Posted on Monday, 21 Sep 2015

A short blog post today but one I still feel will be helpful to a few of you.

Recently I was writing some Javascript for a responsive HTML5 front end that I was working on and needed to find out what CSS media breakpoint the browser was currently in. Naturally my initial reaction was to use Javascript to detect the browser width and go from there; however doing it this way immediately felt dirty as it would result in a duplication of breakpoint values throughout the application - something I was keen to avoid.

After a bit of head-scratching the solution I ended up with was to target the device specific show/hide classes that most CSS framework provide.

In the following primitive example I'm using the Unsemantic CSS grid framework, but almost all CSS frameworks provide similar classes - though even if you're not using a framework there's nothing to stop you from creating your own.

HTML:

<a href="#" id="clickMeButton">Click Me</a>

<!-- These can go just before the </body> tag -->
<div class="show-on-desktop"></div>
<div class="show-on-mobile"></div>

CSS:

.show-on-desktop { display: none;}
.show-on-mobile { display: none; }

/* Mobile */
@media (max-width: 300px) { 
    .show-on-mobile { display: block; }
}

/* Desktop */
@media (min-width: 301px) {    
    .show-on-desktop { display: block; }
}

Javascript:

$(function(){

   $('#clickMeButton').on('click', function(){
       if($('.show-on-desktop').is(':visible')){
           alert('desktop');
       } else if ($('.show-on-mobile').is(':visible')){
           alert('mobile'); 
       }
	}); 

});

You can check out this JSFiddle to see a working example of the above code - if you resize the browser and click the button you'll notice the alert message will change from "Desktop" to "Mobile".

Whilst looking at similar solutions I found this StackOverflow answer which goes one further and turns the same approach into a Bootstrap plugin for easier use - awesome!

Back