JAVASCRIPT
Toggle CSS Class on Click Event for UI Interactivity
Implement dynamic UI behavior by toggling CSS classes on HTML elements when a button or element is clicked, perfect for interactive components like menus.
document.addEventListener('DOMContentLoaded', () => {
const toggleButton = document.getElementById('toggleButton');
const targetElement = document.getElementById('targetElement');
if (toggleButton && targetElement) {
toggleButton.addEventListener('click', () => {
targetElement.classList.toggle('active');
console.log(`'active' class toggled on #targetElement. Current state: ${targetElement.classList.contains('active')}`);
});
} else {
console.warn('Required elements (toggleButton or targetElement) not found in the DOM.');
}
});
// HTML Example (place in your body):
// <button id="toggleButton">Toggle State</button>
// <div id="targetElement" style="width: 100px; height: 100px; background-color: lightblue;"></div>
// CSS Example (place in your style sheet):
// .active { background-color: darkblue; color: white; border: 2px solid #333; }
How it works: This snippet demonstrates how to add interactivity to your web page by toggling a CSS class on an element when another element is clicked. It waits for the DOM to be fully loaded, then identifies a `toggleButton` and a `targetElement`. An event listener is attached to the button, which, on click, calls `targetElement.classList.toggle('active')`. This method efficiently adds the 'active' class if it's not present, or removes it if it is, allowing you to control visual states like active/inactive, visible/hidden, or different styling themes.