javascript button state
CSS

Toggle Active Button State with JavaScript

JavaScript code snippet to add “active” class to any button or div to toggle an active state. Useful for changing styles and appearance of clicked button. The snippet below will add click event listener to element with “myDiv” ID. Then add “active” class or remove instead if already added.

Snippet 1 (Vanilla JavaScript)

document.getElementById("myDiv")
.addEventListener("click", function() {
  if (this.classList.contains("active")) {
    this.classList.remove("active");
  } else this.classList.add("active");
});

Example

This example uses the snippet above to track the button cover open/close state.

Snippet 2 (with jQuery)

$('#myDiv').click(function(){
   $(this).toggleClass('active');
});
Note
Some developers use the checkbox “hack” to store button state instead of using JavaScript. You might want to look into this if you’re looking for pure CSS approach.

Example

Codepen Example

Leave a Reply

Your email address will not be published. Required fields are marked *