Categories
JavaScript Answers

How to toggle visibility property of a div with JavaScript?

Spread the love

Sometimes, we want to toggle visibility property of a div with JavaScript.

In this article, we’ll look at how to toggle visibility property of a div with JavaScript.

How to toggle visibility property of a div with JavaScript?

To toggle visibility property of a div with JavaScript, we set the style.visibility property.

For instance, we write

const toggleVideo = () => {
  const e = document.getElementById("video-over");
  if (e.style.visibility === "visible") {
    e.style.visibility = "hidden";
  } else if (e.style.visibility === "hidden") {
    e.style.visibility = "visible";
  }
};

to define the toggleVideo function.

In it, we get the element with getElementById.

Then we check if it’s visible with e.style.visibility === "visible".

If it’s true, we set it toi 'hidden'.

Otherwise, we set it to 'visible'.

Conclusion

To toggle visibility property of a div with JavaScript, we set the style.visibility property.

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 *