JAVASCRIPT
Toggling CSS Classes for Interactive UI Elements
Discover how to add, remove, and toggle CSS classes on DOM elements using JavaScript's classList API for creating dynamic and interactive user interfaces.
const toggleButton = document.getElementById('toggleBtn');
const targetElement = document.getElementById('myElement');
// Assume 'myElement' is a div with some initial style
// and 'active' class would change its background, for example.
// CSS for 'active' class:
// .active { background-color: #ffeb3b; border-color: #fdd835; }
toggleButton.addEventListener('click', () => {
targetElement.classList.toggle('active');
if (targetElement.classList.contains('active')) {
console.log('Element is now active.');
toggleButton.textContent = 'Deactivate Element';
} else {
console.log('Element is now inactive.');
toggleButton.textContent = 'Activate Element';
}
});
console.log('Class toggle setup complete.');
How it works: This snippet illustrates how to efficiently toggle a CSS class on an element using `classList.toggle()`. A click handler on `toggleButton` is set up to add or remove the 'active' class from `myElement`. This is a common pattern for managing the visual state of elements, such as showing/hiding content, highlighting selections, or changing styles based on user interaction.