JAVASCRIPT
Toggle Element Visibility with JavaScript
Efficiently show or hide any HTML element on a webpage by directly manipulating its display CSS property using JavaScript, improving user interface interactivity.
function toggleVisibility(elementId) {
const element = document.getElementById(elementId);
if (element) {
if (element.style.display === 'none') {
element.style.display = ''; // Revert to default display (e.g., block, inline-block)
} else {
element.style.display = 'none';
}
}
}
// Usage:
// Assuming an HTML element like: <div id="myBox" style="background: lightblue; padding: 20px;">Hello World</div>
// To toggle visibility via a button click:
const toggleButton = document.getElementById('toggleButton');
if (toggleButton) {
toggleButton.addEventListener('click', () => {
toggleVisibility('myBox');
});
}
How it works: This function takes an element's ID and toggles its visibility. It checks the current value of the `display` CSS property. If it's 'none', it sets it to an empty string, which reverts the element to its default display value (e.g., 'block' for a div, 'inline' for a span). If it's anything else, it sets `display` to 'none', effectively hiding the element. This is a common pattern for simple show/hide UI behaviors.