Last active
August 29, 2015 14:01
-
-
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.
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
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