Categories
JavaScript Answers

How to toggle show or hide div with button with JavaScript?

Spread the love

Sometimes, we want to toggle show or hide div with button with JavaScript.

In this article, we’ll look at how to toggle show or hide div with button with JavaScript.

How to toggle show or hide div with button with JavaScript?

To toggle show or hide div with button with JavaScript, we can set the style property of the element we’re showing or hiding when we click on a button.

For instance, we write

const button = document.getElementById("button");

button.onclick = () => {
  const div = document.getElementById("newpost");
  if (div.style.display !== "none") {
    div.style.display = "none";
  } else {
    div.style.display = "block";
  }
};

to select the button with getElementById.

Then set set button.onclick to a function that runs when we click on button.

In it, we select the element we want to toggle show or hide with getElementById.

If its display CSS property isn’t 'none', then we set it to 'none'.

Otherwise, we set it to 'block'.

Conclusion

To toggle show or hide div with button with JavaScript, we can set the style property of the element we’re showing or hiding when we click on a button.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.