Skip to content

Instantly share code, notes, and snippets.

@ricardozea
Created November 15, 2016 13:10
Show Gist options
  • Save ricardozea/56e1b5f96cd8d28d8d95b84cf28e0265 to your computer and use it in GitHub Desktop.
Save ricardozea/56e1b5f96cd8d28d8d95b84cf28e0265 to your computer and use it in GitHub Desktop.
Add/Remove a class in the <body> tag at specific breakpoints.
/*
* Add/Remove a class in the <body> tag at specific breakpoints
* Thanks to:
* Jon Daiello - https://twitter.com/jondaiello
* Nate Denlinger - https://twitter.com/natedenlinger
*/
var breakpoints = [
{ class: "accordion", width: 640 }, //edit
//{class: "another-class", width: 756}
];
function setWidthClasses(element) {
var elementWidth = element.offsetWidth;
for (var x = 0; x < breakpoints.length; x++) {
if (window.innerWidth < breakpoints[x].width) {
element.classList.add(breakpoints[x].class)
} else {
element.classList.remove(breakpoints[x].class)
}
}
}
var targetElement = document.body;
window.onload = setWidthClasses(targetElement);
window.onresize = function() {
setWidthClasses(targetElement)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment