JAVASCRIPT

Toggle Element Visibility with Class List

Learn to easily show or hide DOM elements or apply/remove conditional styles by toggling CSS classes using JavaScript's `classList` API for interactive UIs.

const toggleButton = document.getElementById('toggleVisibilityBtn');
const targetBox = document.getElementById('contentToToggle');

if (toggleButton && targetBox) {
  // Initial setup: Add 'hidden' class if element should start hidden
  // targetBox.classList.add('hidden'); 

  toggleButton.addEventListener('click', () => {
    targetBox.classList.toggle('hidden');
    // 'hidden' class could be defined in CSS as: .hidden { display: none; visibility: hidden; }

    const isHidden = targetBox.classList.contains('hidden');
    toggleButton.textContent = isHidden ? 'Show Content' : 'Hide Content';
    targetBox.setAttribute('aria-hidden', isHidden ? 'true' : 'false'); // Accessibility
  });
} else {
  console.warn('Toggle button or target box not found.');
}
How it works: This code snippet demonstrates a common pattern for toggling element visibility or state. It attaches a click event listener to a button. When clicked, it uses `classList.toggle('hidden')` to add or remove a pre-defined 'hidden' CSS class from a target element. This effectively shows or hides the element without direct inline style manipulation, promoting cleaner CSS. It also updates the button's text and `aria-hidden` attribute for accessibility.

Need help integrating this into your project?

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

Hire DigitalCodeLabs