JAVASCRIPT

Toggle CSS Classes for Dynamic Element Styling

Master the `classList.toggle()` method in JavaScript to easily add or remove CSS classes from elements, enabling dynamic styling and interactive UI components with minimal code.

function setupClassToggle(buttonId, targetElementId, className) {
  const button = document.getElementById(buttonId);
  const targetElement = document.getElementById(targetElementId);

  if (!button || !targetElement) {
    console.error("Button or target element not found.");
    return;
  }

  button.addEventListener('click', () => {
    targetElement.classList.toggle(className);
    console.log(`Class '${className}' toggled on #${targetElementId}. Current state: ${targetElement.classList.contains(className)}`);
  });
}

// Example usage:
// In your HTML:
// <button id="toggleBtn">Toggle Style</button>
// <div id="myBox" class="default-style">This box changes style.</div>
// In your CSS:
// .default-style { border: 1px solid black; padding: 10px; }
// .highlight-style { background-color: yellow; color: blue; }
// Call it: setupClassToggle('toggleBtn', 'myBox', 'highlight-style');
How it works: This code provides a simple yet powerful way to dynamically change an element's appearance by toggling a CSS class. The `classList.toggle()` method adds a specified class if it doesn't exist on the element, and removes it if it does. This is incredibly useful for interactive UI components like navigation menus, tabs, or modal dialogs, where an element's state (e.g., 'active', 'open', 'hidden') is visually represented by a CSS class.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs