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:
- 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; }
- Next, create a button element in your HTML file:
<button id="myButton" class="inactive">Click me</button>
- 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 });
- 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.