JAVASCRIPT
Toggle CSS Classes for Dynamic UI State Management
Efficiently switch UI states by adding or removing CSS classes using `classList.toggle()`, creating interactive and responsive user interfaces with clean and concise code.
const toggleButton = document.getElementById('toggleStateBtn');
const targetBox = document.getElementById('myBox');
toggleButton.addEventListener('click', () => {
// Toggle the 'active' class on the targetBox element
targetBox.classList.toggle('active');
// Optionally, toggle text on the button based on the class state
if (targetBox.classList.contains('active')) {
toggleButton.textContent = 'Deactivate Box';
} else {
toggleButton.textContent = 'Activate Box';
}
});
// Example for a navigation menu
const menuButton = document.getElementById('menuToggle');
const navMenu = document.getElementById('navMenu');
menuButton.addEventListener('click', () => {
navMenu.classList.toggle('open');
menuButton.classList.toggle('rotated-icon'); // Example for a hamburger icon animation
});
/* HTML Structure Example:
<button id="toggleStateBtn">Activate Box</button>
<div id="myBox" style="width: 100px; height: 100px; background-color: lightgray; margin-top: 10px; transition: all 0.3s ease;"></div>
<button id="menuToggle">☰</button>
<nav id="navMenu" style="display: none; background: #eee; padding: 10px;">Menu Items...</nav>
CSS Example:
#myBox.active {
background-color: dodgerblue;
border-radius: 50%;
transform: scale(1.2);
}
#navMenu.open {
display: block;
}
.rotated-icon {
transform: rotate(90deg);
transition: transform 0.3s ease;
}
*/
How it works: The `classList.toggle()` method provides a concise way to add or remove a CSS class from an element. If the class is present, it removes it; if it's absent, it adds it. This is extremely useful for managing UI states, such as showing/hiding elements, applying different styles based on user interaction (like an 'active' state for a button), or animating components. By separating styling from JavaScript logic through CSS classes, the code becomes cleaner, more maintainable, and allows for easier visual updates without touching the JavaScript.