Categories
JavaScript Answers

How to make a div visible and invisible with JavaScript?

Spread the love

You can make a <div> element visible or invisible in JavaScript by manipulating its CSS display property.

To do this, we write:

HTML:

<div id="myDiv">This is a div</div>
<button onclick="toggleVisibility()">Toggle Visibility</button>

JavaScript:

function toggleVisibility() {
    var div = document.getElementById('myDiv');
    if (div.style.display === 'none') {
        div.style.display = 'block'; // or 'inline', 'inline-block', etc. depending on your layout
    } else {
        div.style.display = 'none';
    }
}

In this example, we have a <div> element with the id myDiv and a button labeled “Toggle Visibility”.

When the button is clicked, the toggleVisibility function is called.

Inside the toggleVisibility function, we get a reference to the <div> element using getElementById.

We then check the current value of the display property of the <div> element.

If it’s 'none', we change it to 'block' (or another appropriate value to make it visible).

If it’s not 'none', we set it to 'none' to make the <div> invisible.

This approach toggles the visibility of the <div> between visible and invisible each time the button is clicked.

Adjust the display property value to match your layout requirements (e.g., 'inline', 'inline-block', etc.).

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *