Skip to content

Instantly share code, notes, and snippets.

@rhernandog
Last active January 7, 2018 16:19
Show Gist options
  • Save rhernandog/7bebf14a9709f1c8ae698b4b1fab9913 to your computer and use it in GitHub Desktop.
Save rhernandog/7bebf14a9709f1c8ae698b4b1fab9913 to your computer and use it in GitHub Desktop.
Vanilla class toggle function
// this function assumes that the target is a DOM element
function classToggle(element, name) {
var target = element.target;
var classEx = new RegExp(" " + name + "|" + name + " ", "g");
if (target.classList) {
// there's support for the class list API
if (target.classList.contains(name)) {
target.classList.remove(name);
} else {
target.classList.add(name);
}
} else {
// no support for the class list api
if (target.className.match(classEx)) {
console.log("remove class");
// the class is present on the element
target.className = target.className.replace(classEx, "");
} else {
console.log("add class")
// the class is not present
target.className = target.className.concat(" " + name);
}
} // class list api conditional
};
/*
If you want to use the code directly on an element's event use the following code.
This is an example of an element being clicked, such as a button. We're toggling the
green class in this one.
*/
btn.onclick = function (e) {
var target = e.target;
var classEx = / green|green /g;
if (target.classList) {
// there's support for the class list API
if (target.classList.contains("green")) {
target.classList.remove("green");
} else {
target.classList.add("green");
}
} else {
// no support for the class list api
if (target.className.match(classEx)) {
console.log("remove class");
// the class is present on the element
target.className = target.className.replace(classEx, "");
} else {
console.log("add class")
// the class is not present
target.className = target.className.concat(" green");
}
} // class list api conditional
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment