Skip to content

Instantly share code, notes, and snippets.

@0frasure
Last active March 30, 2017 12:55
Show Gist options
  • Save 0frasure/a23ed800ee5753369abe to your computer and use it in GitHub Desktop.
Save 0frasure/a23ed800ee5753369abe to your computer and use it in GitHub Desktop.
Javascript Toggle CSS Styles
<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