Skip to content

Instantly share code, notes, and snippets.

@bootsified
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save bootsified/47b79fbf12ff7eccef66 to your computer and use it in GitHub Desktop.

Select an option

Save bootsified/47b79fbf12ff7eccef66 to your computer and use it in GitHub Desktop.
Test CSS media query breakpoints in JS. Inspired by what I found here: http://adactio.com/journal/5429/
/* This is what I use near the top of my CSS stylesheet */
/* Mobile first! (767px and below) */
body:after {
display: none;
content: 'phone';
}
/* Small Devices, Tablets (kicks in at 768px) */
@media only screen and (min-width : 768px) {
body:after {
content: 'tablet';
}
}
/* Medium Devices, Desktops (kicks in at 992px) */
@media only screen and (min-width : 992px) {
body:after {
content: 'laptop';
}
}
/* Large Devices, Wide Screens (kicks in at 1200px) */
@media only screen and (min-width : 1200px) {
body:after {
content: 'widescreen';
}
}
/* Something like this would go in my scripts.js file, if needed.*/
// Init the current breakpoint variable
var current_bp;
// Set a browser resize listener
$( window ).resize(function() {
// Get the content of the body's ':after' pseudo-element
// This value changes in the CSS depending on the media query
var new_bp = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
// Tidy up after inconsistent browsers (some include quotation marks, they shouldn't)
new_bp = new_bp.replace(/"/g, "");
new_bp = new_bp.replace(/'/g, "");
// If the new breakpoint is different from the old one, do some stuff
if (current_bp != new_bp) {
switch (new_bp) {
case "phone":
// Do some stuff here for phones
break;
case "tablet":
// Do some stuff here for tablets
break;
case "laptop":
// Do some stuff here for smaller desktops/laptops
break;
case "widescreen":
// Do some stuff here for large desktops
break;
default:
// Not a breakpoint, so do nothing.
} // end switch
// Update 'current_bp' var
current_bp = new_bp;
} // end if
}); // end resize listener
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment