JAVASCRIPT
Toggle a CSS Class on Click
Implement interactive UI elements by toggling CSS classes on click using `classList.toggle()` for dynamic styling and behavior without complex state management.
// HTML Example:
// <button id="toggleButton" class="btn">Toggle Active State</button>
// <div id="myBox" class="box"></div>
// CSS Example:
// .box { width: 100px; height: 100px; background-color: lightblue; transition: background-color 0.3s ease; }
// .box.active { background-color: salmon; border: 2px solid red; }
document.addEventListener('DOMContentLoaded', () => {
const toggleButton = document.getElementById('toggleButton');
const myBox = document.getElementById('myBox');
if (toggleButton && myBox) {
toggleButton.addEventListener('click', () => {
myBox.classList.toggle('active');
console.log('Class "active" toggled. Current classes:', myBox.classList);
});
}
});
How it works: This code illustrates how to dynamically add or remove a CSS class from an HTML element using `classList.toggle()`. When the specified button is clicked, the `active` class is added to `myBox` if it's not present, or removed if it is. This is a common pattern for interactive elements like navigation menus, tabs, or accordions, changing their visual state based on user interaction.