JavaScript

Toggle Visibility of HTML Elements with JavaScript

Toggle Hide and Show an Element

Element visibility toggling is a fundamental technique in web development that allows developers to create interactive user interfaces. This approach uses the CSS display property to control element visibility, providing smooth user experiences without removing elements from the DOM.

Implementation Steps

Step 1: Create HTML Structure

Begin by setting up the HTML elements that will be toggled. The structure includes a control button and target elements:

<button id="toggleBtn" onclick="toggleFunction()">Click to Hide Elements</button>
<input type="text" id="myInput" value="Sample input text content">
<select id="mySelect">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
</select>

Step 2: Add Initial CSS Styling

Define initial styles to ensure proper element display and user experience:

#myInput, #mySelect {
    display: block;
    margin: 10px 0;
}

#toggleBtn {
    padding: 10px 15px;
    cursor: pointer;
}

Step 3: Implement JavaScript Toggle Function

Create the JavaScript function that handles the visibility toggle logic:

function toggleFunction() {
    var inputElement = document.getElementById("myInput");
    var selectElement = document.getElementById("mySelect");
    var toggleButton = document.getElementById("toggleBtn");
    
    if (inputElement.style.display === "none") {
        inputElement.style.display = "block";
        selectElement.style.display = "block";
        toggleButton.innerHTML = "Click to Hide Elements";
    } else {
        inputElement.style.display = "none";
        selectElement.style.display = "none";
        toggleButton.innerHTML = "Click to Show Elements";
    }
}

How It Works

The toggle function operates by:

  1. Element Selection: Retrieving references to target elements using getElementById()
  2. State Detection: Checking the current display style property value
  3. Conditional Logic: Applying opposite visibility state based on current condition
  4. Button Text Update: Modifying button text to reflect the next available action

Alternative Approaches

Using CSS Classes

Instead of directly manipulating the display property, consider using CSS classes for better maintainability:

.hidden {
    display: none;
}
function toggleWithClass() {
    var elements = [
        document.getElementById("myInput"),
        document.getElementById("mySelect")
    ];
    
    elements.forEach(function(element) {
        element.classList.toggle("hidden");
    });
}

Using Visibility Property

For scenarios where element space should be preserved:

function toggleVisibility() {
    var inputElement = document.getElementById("myInput");
    var selectElement = document.getElementById("mySelect");
    
    var isVisible = inputElement.style.visibility !== "hidden";
    
    inputElement.style.visibility = isVisible ? "hidden" : "visible";
    selectElement.style.visibility = isVisible ? "hidden" : "visible";
}

Accessibility Considerations

When implementing element toggling, ensure accessibility compliance:

  • Add aria-expanded attributes to control buttons
  • Use aria-hidden for decorative elements
  • Provide screen reader announcements for state changes
  • Ensure keyboard navigation remains functional
<button id="toggleBtn" aria-expanded="true" aria-controls="myInput mySelect">
    Toggle Elements
</button>

Browser Compatibility

This technique works across all modern browsers including:

  • Chrome 1+
  • Firefox 1+
  • Safari 1+
  • Internet Explorer 5.5+
  • Edge (all versions)

Common Use Cases

  • Form field conditional display
  • Progressive disclosure interfaces
  • Navigation menu toggles
  • Content accordion implementations
  • Modal dialog controls

Troubleshooting

Elements not hiding/showing: Ensure element IDs match exactly in HTML and JavaScript

Initial state issues: Set explicit CSS display values rather than relying on browser defaults

Button text not updating: Verify button element reference is correct and accessible

Complete Example

Here’s the full working implementation:

<!DOCTYPE html>
<html>
<head>
    <style>
        #myInput, #mySelect {
            display: block;
            margin: 10px 0;
            padding: 8px;
        }
        #toggleBtn {
            padding: 10px 15px;
            cursor: pointer;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <button id="toggleBtn" onclick="toggleFunction()">Click to Hide Elements</button>
    <input type="text" id="myInput" value="Sample input text content">
    <select id="mySelect">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
    </select>

    <script>
        function toggleFunction() {
            var inputElement = document.getElementById("myInput");
            var selectElement = document.getElementById("mySelect");
            var toggleButton = document.getElementById("toggleBtn");
            
            if (inputElement.style.display === "none") {
                inputElement.style.display = "block";
                selectElement.style.display = "block";
                toggleButton.innerHTML = "Click to Hide Elements";
            } else {
                inputElement.style.display = "none";
                selectElement.style.display = "none";
                toggleButton.innerHTML = "Click to Show Elements";
            }
        }
    </script>
</body>
</html>

Summary

Element visibility toggling provides an essential foundation for interactive web interfaces. This technique offers developers precise control over content display while maintaining clean, accessible user experiences. The display property approach ensures complete element hiding, making it ideal for conditional form fields, progressive disclosure patterns, and dynamic content management.

For enhanced functionality, consider combining this technique with CSS transitions, animation libraries, or modern JavaScript frameworks to create more sophisticated user interface behaviors.

Try it Yourself

You can try this example yourself in your own HTML file. Just copy the HTML and JavaScript code into your file, open it in a web browser, and click the button to see the input and select elements show and hide.

Happy coding!

📂 Get the Full Source Code! 📚Click here to download the full source code

Visit our YouTube: CodeLSC Channel and website: CodePro Blog for additional resources, articles, and more!