JAVASCRIPT

Toggle CSS Class on Element Click

Learn how to efficiently toggle a CSS class on an HTML element using JavaScript's classList.toggle() method in response to a click event, ideal for interactive UI components.

document.addEventListener('DOMContentLoaded', () => {
  const toggleButton = document.getElementById('myToggleButton');
  const targetElement = document.getElementById('myTargetElement');

  if (toggleButton && targetElement) {
    toggleButton.addEventListener('click', () => {
      targetElement.classList.toggle('active');
      console.log(`Class 'active' on target element: ${targetElement.classList.contains('active') ? 'added' : 'removed'}`);
    });
  }
});
How it works: This snippet demonstrates how to dynamically add or remove a CSS class from an element using the `classList.toggle()` method. When the button with ID 'myToggleButton' is clicked, the 'active' class is either added to or removed from the 'myTargetElement'. This is a very common pattern for creating interactive UI elements like menus, modals, or accordion sections, where a visual state change is required based on user interaction. The `DOMContentLoaded` event ensures the script runs only after the entire HTML document has been loaded and parsed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs