ricardozea
11/15/2016 - 1:10 PM

Add/Remove a class in the <body> tag at specific breakpoints.

Add/Remove a class in the 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)
};