Toggle classname onclick JavaScript

Toggle classname onclick JavaScript

I am really surprised nobody mentioned classList here. So just to be complete: Alternative solution would be to use classList method toggle().

Your case would then simply be:

document.getElementById(myButton).onclick = function() {
    this.classList.toggle(active);
}

e.classList.toggle() has good support (except for, ehm, IE, Its there since IE10). Click here for complete browser compatibility.

If you want to use a ternary operator, use this:

document.getElementById(myButton).onclick = function() {

    var className =   + myButton.className +  ;

    this.className = ~className.indexOf( active ) ?
                         className.replace( active ,  ) :
                         this.className +  active;
}

For clarity, Id use a regular if/else:

document.getElementById(myButton).onclick = function() {

    var className =   + myButton.className +  ;

    if ( ~className.indexOf( active ) ) {
        this.className = className.replace( active ,  );
    } else {
        this.className +=  active;
    }              
}

Heres the fiddle: http://jsfiddle.net/ttEGY/

Toggle classname onclick JavaScript

If JQuery is okay for you it really is as simple as

$(myButton).toggleClass(active)

http://jsfiddle.net/bikeshedder/eRJB4/

Leave a Reply

Your email address will not be published.