Since you just want to support IE9+ this should do the trick:
function toggleClass(elem,cls) {
var classes = elem.className.split(/\s+/);
var search = classes.indexOf(cls);
if(search >= 0) {
classes.splice(search,1);
} else {
classes.push(cls);
}
elem.className = classes.join(' ');
}
function menuOpen() {
var cls = 'mobile-menu-open';
toggleClass(document.body,cls);
if(document.body.className.split(/\s+/).indexOf(cls) >= 0) {
console.log('menu open'); }
}
function init() {
var mobileButtons = document.querySelectorAll('[data-js="mobile-menu"]');
if(mobileButtons.length>0) {
mobileButtons[0].addEventListener('click',menuOpen,false);
}
}
document.addEventListener('DOMContentLoaded',init,false);
The other events I had you look at were in case you wanted to develop something that also supports antiquated versions of IE.
Note: If you value performance, querySelectorAll
is not particularly fast so you may have better results doing getElementsByTagName('*')
first (or a more specific tag name if possible) then looping through the resultant nodeList
.
Edit: Instead of using classList
I'm just using the className
attribute and splitting it by whitespace to get an array of classes. It searches for the given class name in that array. If it finds it, it removes it by the index, and if it doesn't, it adds it. It then sets className
to the array joined with spaces.