Last active
December 21, 2015 05:18
-
-
Save ianpgall/6255438 to your computer and use it in GitHub Desktop.
JavaScript function to manage CSS classes (detects native browser support)
This file contains hidden or 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
var Classes = (function () { | |
"use strict"; | |
var E, trim, containsClass, addClass, removeClass, toggleClass; | |
E = document.createElement("div"); | |
if (E.classList && !E.hasOwnProperty("classList")) { | |
containsClass = function (el, cls) { | |
return el.classList.contains(cls); | |
}; | |
addClass = function (el, cls) { | |
return el.classList.add(cls); | |
}; | |
removeClass = function (el, cls) { | |
return el.classList.remove(cls); | |
}; | |
toggleClass = function (el, cls) { | |
return el.classList.toggle(cls); | |
}; | |
} else { | |
trim = (function () { | |
var S, re, func; | |
S = ""; | |
re = /^\s+|\s+$/g; | |
if (S.trim && !S.hasOwnProperty("trim")) { | |
func = function (str) { | |
str = "" + (str || ""); | |
return S.trim.call(str); | |
}; | |
} else { | |
func = function (str) { | |
str = "" + (str || ""); | |
return str.replace(re, ""); | |
}; | |
} | |
return func; | |
}()); | |
containsClass = function (el, cls) { | |
return !!~(" " + el.className + " ").indexOf(" " + cls + " "); | |
}; | |
addClass = function (el, cls) { | |
if (!containsClass(el, cls)) { | |
el.className += " " + cls; | |
return true; | |
} | |
return false; | |
}; | |
removeClass = function (el, cls) { | |
el.className = trim((" " + el.className + " ").replace(" " + cls + " ")); | |
}; | |
toggleClass = function (el, cls) { | |
if (!addClass(el, cls)) { | |
removeClass(el, cls); | |
} | |
}; | |
} | |
return { | |
contains: containsClass, | |
add: addClass, | |
remove: removeClass, | |
toggle: toggleClass | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment