JAVASCRIPT

Toggle Element Visibility (Show/Hide) with JavaScript

Learn how to quickly show or hide any HTML element using JavaScript by manipulating its `display` CSS property or `hidden` attribute for simple UI toggles.

function toggleVisibility(elementId, method = 'display') {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error(`Element with ID '${elementId}' not found.`);
        return;
    }

    if (method === 'display') {
        // Toggle using CSS display property
        if (element.style.display === 'none') {
            element.style.display = ''; // Revert to default or previous display value
            console.log(`Element '${elementId}' is now visible (display='').`);
        } else {
            element.style.display = 'none';
            console.log(`Element '${elementId}' is now hidden (display='none').`);
        }
    } else if (method === 'hidden') {
        // Toggle using HTML hidden attribute
        element.hidden = !element.hidden;
        console.log(`Element '${elementId}' hidden attribute set to: ${element.hidden}.`);
    } else {
        console.error(`Invalid method '${method}'. Use 'display' or 'hidden'.`);
    }
}

// Example Usage:
// Assuming you have: <div id="myBox">This is a box.</div>
// toggleVisibility('myBox', 'display'); // Hides myBox
// toggleVisibility('myBox', 'display'); // Shows myBox
// <p id="anotherBox">Another box.</p>
// toggleVisibility('anotherBox', 'hidden'); // Hides anotherBox
// toggleVisibility('anotherBox', 'hidden'); // Shows anotherBox
How it works: This snippet provides a flexible function to toggle the visibility of an HTML element. It supports two common methods: by manipulating the `element.style.display` CSS property (setting it to 'none' or reverting to its default) or by toggling the `element.hidden` boolean attribute. Both approaches offer simple ways to show or hide elements, useful for interactive UI components like expandable sections, modals, or notification messages.

Need help integrating this into your project?

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

Hire DigitalCodeLabs