JAVASCRIPT

Toggle UI Element State Using ClassList

Master toggling CSS classes on DOM elements to manage UI states like active/inactive or visible/hidden, creating interactive and responsive user interfaces with JavaScript.

function toggleElementState(elementId, className) {
  const element = document.getElementById(elementId);
  if (element) {
    element.classList.toggle(className);
    console.log(`Class '${className}' toggled on element '${elementId}'. Current state: ${element.classList.contains(className) ? 'active' : 'inactive'}.`);
  } else {
    console.warn(`Element with ID '${elementId}' not found.`);
  }
}

// Example Usage:
// Assume the following HTML:
// <button id="toggleButton">Toggle Content</button>
// <div id="contentDiv" class="hidden">
//   This content will be toggled.
// </div>
// And CSS:
// .hidden { display: none; }
// .visible { display: block; background-color: lightyellow; padding: 10px; }

const toggleButton = document.getElementById('toggleButton');
if (toggleButton) {
  toggleButton.addEventListener('click', () => {
    // Toggle a 'visible' class, which might reveal content currently 'hidden'
    toggleElementState('contentDiv', 'visible');

    // You could also directly toggle a 'hidden' class if your CSS is set up that way
    // toggleElementState('contentDiv', 'hidden');
  });
} else {
  console.error("Toggle button with ID 'toggleButton' not found.");
}
How it works: The `classList` API provides a convenient way to manage CSS classes on an element, which is essential for changing UI states. The `toggle()` method is particularly useful: it adds a class if it's not present and removes it if it is. This snippet demonstrates how to use `classList.toggle()` to switch between different visual states, such as showing or hiding content. By defining corresponding CSS rules (e.g., `.hidden { display: none; }` and `.visible { display: block; }`), you can create interactive UI components with minimal JavaScript.

Need help integrating this into your project?

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

Hire DigitalCodeLabs