Adding an Active Class to a Button on Click Using JavaScript
This tutorial will guide you through adding an active class to a button when it is clicked using JavaScript. This technique is commonly used to visually highlight the selected button in a group, providing user feedback and improving user experience.
Understanding the Concept
The core idea is to use JavaScript to toggle the presence of a CSS class ("active" in this example) on the button element when it's clicked. This class will contain the necessary styles (e.g., background color, border, etc.) to visually indicate the active state.
HTML Setup
First, we need to set up our HTML structure. Here's a simple example with two buttons:
Active Button Example
JavaScript Implementation
Now, let's add the JavaScript code to handle the click event and toggle the "active" class:
const button1 = document.getElementById("button1");
const button2 = document.getElementById("button2");
button1.addEventListener("click", function() {
// Remove active class from all buttons
button1.classList.remove("active");
button2.classList.remove("active");
// Add active class to the clicked button
this.classList.add("active");
});
button2.addEventListener("click", function() {
// Remove active class from all buttons
button1.classList.remove("active");
button2.classList.remove("active");
// Add active class to the clicked button
this.classList.add("active");
});
Explanation
- Get Element References: We select the button elements using
document.getElementById()
. - Event Listener: We attach an event listener to each button using
addEventListener("click", function() {})
. This function will execute when the button is clicked. - Remove Active Class: Inside the event handler, we use
classList.remove("active")
to remove the "active" class from both buttons, ensuring only one button is active at a time. - Add Active Class:
this.classList.add("active")
adds the "active" class to the clicked button (this
refers to the clicked button).
Key Points
- The
classList
property provides methods to manage classes on an element:classList.add(className)
: Adds a class.classList.remove(className)
: Removes a class.classList.toggle(className)
: Toggles the presence of a class.
- The
this
keyword inside the event handler refers to the clicked element.
Conclusion
By combining simple HTML and JavaScript, you can easily add an active class to a button on click, making your web applications more interactive and user-friendly. This approach allows you to visually highlight the selected button and provide clear feedback to the user.