JAVASCRIPT
Toggle CSS Classes for Dynamic UI States with JavaScript
Learn how to easily add, remove, or toggle CSS classes on DOM elements using JavaScript's `classList` API to manage interactive UI states like active, hidden, or selected.
const toggleButton = document.getElementById('toggleBtn');
const targetElement = document.getElementById('myBox');
if (toggleButton && targetElement) {
toggleButton.addEventListener('click', () => {
// Toggle a single class
targetElement.classList.toggle('active');
// Add a class if not present
if (!targetElement.classList.contains('highlight')) {
targetElement.classList.add('highlight');
} else {
// Remove a class if present
targetElement.classList.remove('highlight');
}
// You can also add/remove multiple classes at once
// targetElement.classList.add('class1', 'class2');
// targetElement.classList.remove('classA', 'classB');
console.log('Current classes:', Array.from(targetElement.classList));
});
}
/*
Example HTML and CSS:
<style>
#myBox {
width: 100px;
height: 100px;
background-color: lightgray;
margin-top: 10px;
transition: background-color 0.3s, transform 0.3s;
}
#myBox.active {
background-color: dodgerblue;
transform: scale(1.1);
}
#myBox.highlight {
border: 2px solid orange;
}
</style>
<button id="toggleBtn">Toggle Box State</button>
<div id="myBox"></div>
*/
How it works: The `classList` API provides a convenient way to manipulate an element's CSS classes without directly modifying its `className` string. This snippet demonstrates `toggle()` to add or remove a class based on its presence, `add()` to ensure a class is present, and `remove()` to ensure it's absent. This approach is ideal for managing UI states (e.g., active, selected, hidden) by applying predefined styles from your CSS stylesheets, leading to cleaner and more maintainable code.