How To Create Active And Inactive Button Using JavaScript?

With JavaScript, you may add or remove a CSS class to the button element based on its state to generate active and inactive buttons. Here’s an example of how to go about it:

  1. First, define two CSS classes for the active and inactive states of the button:
.active {
  background-color: green;
  color: white;
  cursor: pointer;
}

.inactive {
  background-color: gray;
  color: white;
  cursor: not-allowed;
}
  1. Next, create a button element in your HTML file:
<button id="myButton" class="inactive">Click me</button>
  1. In your JavaScript file, select the button element and add an event listener to it:
const myButton = document.querySelector('#myButton');

myButton.addEventListener('click', () => {
  // do something when the button is clicked
});
  1. Inside the event listener, toggle the CSS class of the button based on its state:
myButton.addEventListener('click', () => {
  if (myButton.classList.contains('active')) {
    myButton.classList.remove('active');
    myButton.classList.add('inactive');
  } else {
    myButton.classList.remove('inactive');
    myButton.classList.add('active');
  }
});

In the above example, we determine if the button has the “active” class. If that happens, we delete that class and replace it with the “inactive” class to render the button inactive. If it lacks the “active” class, we delete the “inactive” class and replace it with the “active” class to make the button active.

As the page loads, you can also set the initial state of the button by adding the “active” or “inactive” class to the button element.

Submit a Comment

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

Subscribe

Select Categories