JAVASCRIPT
Toggle Element Visibility with JavaScript and CSS Classes
Implement a straightforward show/hide mechanism for any HTML element by toggling a CSS class using JavaScript's classList API.
// HTML Structure:
// <button id="toggleBtn">Toggle Content</button>
// <div id="myContent" class="hidden">
// This is some content that will be shown or hidden.
// </div>
// Corresponding CSS:
// .hidden {
// display: none;
// }
document.addEventListener('DOMContentLoaded', () => {
const toggleBtn = document.getElementById('toggleBtn');
const myContent = document.getElementById('myContent');
toggleBtn.addEventListener('click', () => {
myContent.classList.toggle('hidden'); // Toggles the 'hidden' class
// Optional: Change button text based on visibility
if (myContent.classList.contains('hidden')) {
toggleBtn.textContent = 'Show Content';
} else {
toggleBtn.textContent = 'Hide Content';
}
});
});
How it works: This snippet demonstrates how to toggle the visibility of an HTML element by adding or removing a specific CSS class. The JavaScript `classList.toggle()` method is used to efficiently switch the presence of the `hidden` class on the target `div`. When the `hidden` class is present, the element is styled with `display: none;` (defined in CSS), making it invisible. This approach is superior to manipulating inline styles for managing element visibility and behavior.