Languages
[Edit]
EN

JavaScript - hide and show element on click event

0 points
Created by:
jarlh
635

In this article, we would like to show you how to hide and show elements using CSS display property with JavaScript.

1. By modifying CSS display property

In this example, we create an invisible element with CSS display property set to none. On button click, we use the handleClick() function to replace the element's class and make it visible.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    .invisible {
      display: none;
    }

    .visible {
      display: block;
    }
  </style>
</head>
<body>
  <button onclick="handleClick()">Hide / Show element</button>
  <div id="element" class="invisible">Some content here ...</div>
  <script>

    var element = document.querySelector('#element');

    function handleClick() {
        if(element.className === 'invisible') {
            element.className = 'visible';
        }
        else {
            element.className = 'invisible';
        }
    }

  </script>
</body>
</html>

2. By modifying CSS visibility property

This example is similar to the first one, but this time, instead of display CSS property, we use visibility. 

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    .invisible {
      visibility: hidden;
    }

    .visible {
      visibility: visible;
    }
  </style>
</head>
<body>
  <button onclick="handleClick()">Hide / Show element</button>
  <div id="element" className="invisible">Some content here ...</div>
  <script>

    var element = document.querySelector('#element');

    function handleClick() {
        if(element.className === 'invisible') {
            element.className = 'visible';
        }
        else {
            element.className = 'invisible';
        }
    }

  </script>
</body>
</html>

See also

  1. JavaScript - hide and show element using placeholder

References

  1. Element.classList - Web APIs | MDN

Alternative titles

  1. JavaScript - hide and show element onclick event
  2. JavaScript - make element appear / disappear on click
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join