[JavaScript] Toggle (Show/Hide) HTML Element


Toggle (Show/Hide) HTML DOM element in JavaScript. See demo first. Please click the following text to toggle the element.



There are two HTML elements in the demo. The HTML code is as follows:

<div class="menu-toggle">
  Click me to toggle
</div>
<div class="invisible menu">
  menu content
</div>

When users click on the first div element, the second div element will become visible if it is invisible, or become invisible if it is visible. In other words, the click of first div toggles the visibility of the second div. To achieve the toggle effect, we need the following CSS classes:

.invisible {
  display: none;
}
.menu-toggle {
  cursor: pointer;
}
.menu {
  width: 200px;
  height: 200px;
  background-color: yellow;
}

The class .invisible will hide the elements that have this class. In the beginning, the second div has .invisible class so it is hidden. Next we will add click event listener to the first div element. In the event listener we will toggle the .invisible class of second div element.

var menu = document.querySelector(".menu");
var menuToggle = document.querySelector(".menu-toggle");
menuToggle.addEventListener("click", function(e) {
  menu.classList.toggle("invisible");
});

It is easy to toggle the .invisible class of DOM element. The classList property of DOM element provides toggle method to toggle CSS class of the DOM element. In the event listener, the invisible class of second div element is toggled, so it is shown/hidden by the clicks of first div element.


Tested on:

  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[1]