JAVASCRIPT
Toggle CSS Classes for Dynamic Styling and Interactivity
Master the `classList.toggle()` method in JavaScript to easily add or remove CSS classes from elements, enabling interactive styling like active states, menus, or dark mode with a single command.
function setupToggleButton(buttonId, targetId, className) {
const button = document.getElementById(buttonId);
const targetElement = document.getElementById(targetId);
if (!button || !targetElement) {
console.error('Button or target element not found.');
return;
}
button.addEventListener('click', () => {
targetElement.classList.toggle(className);
// Optional: Update button text based on state
button.textContent = targetElement.classList.contains(className) ? 'Deactivate' : 'Activate';
});
}
// Example Usage:
// HTML structure:
// <button id="my-button">Activate</button>
// <div id="my-box" style="width: 100px; height: 100px; border: 1px solid black; margin-top: 10px;"></div>
// CSS:
// .active { background-color: lightblue; border-color: blue; }
const toggleBtn = document.createElement('button');
toggleBtn.id = 'my-button';
toggleBtn.textContent = 'Activate';
document.body.appendChild(toggleBtn);
const toggleBox = document.createElement('div');
toggleBox.id = 'my-box';
toggleBox.style.cssText = 'width: 100px; height: 100px; border: 1px solid black; margin-top: 10px;';
document.body.appendChild(toggleBox);
const style = document.createElement('style');
style.textContent = '.active { background-color: lightblue; border-color: blue; }';
document.head.appendChild(style);
setupToggleButton('my-button', 'my-box', 'active');
How it works: This snippet demonstrates the `classList.toggle()` method, a powerful and concise way to add or remove a CSS class from an element based on its current presence. It's ideal for implementing interactive UI elements like toggling active states, showing/hiding components, or switching themes (e.g., dark mode) with minimal and readable code.