javascript button state

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)

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


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

Snippet 2 (with jQuery)

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.


Codepen Example

Leave a Reply

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