Skip to content

Instantly share code, notes, and snippets.

@cramdesign
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cramdesign/d2a7243bc0a339052b8d to your computer and use it in GitHub Desktop.
Save cramdesign/d2a7243bc0a339052b8d to your computer and use it in GitHub Desktop.
A simple javascript function to toggle a class on/off. No need for jquery to build a simple responsive menu or somewhat.
toggleClass = function( el, className ) {
if ( el.classList ) {
el.classList.toggle( className );
} else {
var classes = el.className.split( ' ' );
var existingIndex = classes.indexOf( className );
if (existingIndex >= 0) {
classes.splice( existingIndex, 1 );
} else {
classes.push( className );
}
el.className = classes.join( ' ' );
}
};
/*
EXAMPLE USAGE:
var btn = document.getElementById('menu').getElementsByClassName('toggle')[0];
var tgt = document.getElementById('menu').getElementsByClassName('target')[0];
*/
var btn = document.getElementById( 'menu' );
btn.onclick = function () {
toggleClass( this, 'active' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment