How to toggle between hiding and showing an element with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To toggle between hiding and showing an element with JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   button {
      padding: 10px;
      border: none;
      background-color: rgb(51, 51, 192);
      color: white;
      font-size: 18px;
   }
   .div-visible {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: rgb(210, 230, 173);
      margin-top: 20px;
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Toggle hide and show example</h1>
<button class="toggleDisplay">Hide Div</button>
<h2>Click on the above button to hide the div below</h2>
<div class="div-visible">
This is a div element
</div>
<script>
   document .querySelector(".toggleDisplay") .addEventListener("click", toggleDivDisplay);
   function toggleDivDisplay() {
      var x = document.querySelector(".div-visible");
      if (x.style.display === "none") {
         x.style.display = "block";
      } else {
         x.style.display = "none";
      }
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the “Hide Div” button −

raja
Published on 08-May-2020 13:22:35
Advertisements