Last active
December 15, 2016 12:11
-
-
Save agryson/4244292 to your computer and use it in GitHub Desktop.
This function will append or remove a class from an element cleanly by ensuring whitespace is how it should be.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Attribution: Alexander Gryson (agryson.net) | |
* Appends or removes a class to/from an element | |
* @param {boolean} bool True if appending class, false if removing | |
* @param {string} targetID ID of target element | |
* @param {string} classString Class to be added / removed (case sensitive) | |
*/ | |
function classChange(bool, targetID, classString){ | |
var target = document.getElementById(targetID); | |
var targetPresent; | |
var newClass; | |
if (target.className.indexOf(classString) > 0){ | |
newClass = ' ' + classString; | |
targetPresent = true; | |
} else if(target.className.indexOf(classString) === -1 && target.className.length > 0){ | |
newClass = ' ' + classString; | |
targetPresent = false; | |
}else if(target.className.indexOf(classString) === -1){ | |
newClass = classString; | |
targetPresent = false; | |
}else{ | |
newClass = classString; | |
targetPresent = true; | |
} | |
if(targetPresent && !bool){ | |
target.className = target.className.replace(newClass, ''); | |
} else if (!targetPresent && bool){ | |
target.className += newClass; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternatively, as I've recently discovered, all of this is also natively supported by pure JavaScript