JAVASCRIPT
Toggle Element Visibility or CSS Classes
Discover how to easily toggle the visibility of an HTML element or switch CSS classes using JavaScript, ideal for interactive UI components like menus or accordions.
// HTML structure:
// <button id="toggleButton">Toggle Details</button>
// <div id="detailsBox" class="hidden">
// <p>These are some details that can be shown or hidden.</p>
// </div>
// CSS example (place in your stylesheet):
// .hidden {
// display: none;
// }
// .visible {
// display: block;
// }
const toggleButton = document.getElementById('toggleButton');
const detailsBox = document.getElementById('detailsBox');
toggleButton.addEventListener('click', () => {
// Using classList.toggle for a CSS class (recommended)
detailsBox.classList.toggle('hidden');
// Alternative: Direct style manipulation (less flexible, often discouraged)
// if (detailsBox.style.display === 'none' || detailsBox.style.display === '') {
// detailsBox.style.display = 'block';
// } else {
// detailsBox.style.display = 'none';
// }
});
How it works: This snippet illustrates how to toggle an element's visibility or its CSS classes in JavaScript, a common requirement for interactive UIs. The recommended method is using `element.classList.toggle('className')`, which adds the class if it's not present or removes it if it is. This approach separates presentation (CSS) from behavior (JavaScript), making your code cleaner and easier to maintain. You can define `hidden` or `visible` classes in your stylesheet to control `display` or `opacity` properties.