Last active
March 30, 2017 12:55
-
-
Save 0frasure/a23ed800ee5753369abe to your computer and use it in GitHub Desktop.
Javascript Toggle CSS Styles
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
<style> | |
.red { | |
color:red; | |
} | |
</style> | |
<button id="toggle" onclick="toggle(this.id)">toggle</button> | |
<button id="add" onclick="toggle(this.id)">add</button> | |
<button id="remove" onclick="toggle(this.id)">remove</button> | |
<p id="thetext">some text</p> | |
<script> | |
// If newState is provided add/remove the class accordingly, otherwise toggle theClass | |
function toggleClass(elem, theClass, newState) { | |
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g'); | |
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null)); | |
elem.className=elem.className.replace(matchRegExp, ''); // clear all | |
if (add) elem.className += ' ' + theClass; | |
} | |
function toggle(id) { | |
var elem = document.getElementById('thetext'); | |
if (id=='toggle') toggleClass(elem, 'red'); | |
if (id=='add') toggleClass(elem, 'red', true); | |
if (id=='remove') toggleClass(elem, 'red', false); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment