To toggle (show/hide) an HTML element with a button click you need to do one
simple trick in the onclick handler of that button. Let me show you how it’s done.
The visibility of all HTML elements is determined by the CSS property display.
When the display property is set to none, the HTML element becomes invisible.
To set the scene, let’s create a button with the text TOGGLE and a header
with any text you like.
<body>
<button id="toggler">TOGGLE</button>
<h2 id="target">THIS HEADER IS ABOUT TO DISAPPEAR!</h2>
</body>
Make sure the both the button, and the header are visible and let’s write the onClick handler
for the toggler button.
The logic is straightforward:
- Get the HTML element by
id - Check if it’s visible
- Change its display style to be either
blockornonebased on the current state
<head>
<script>
function toggle(elementId) {
const element = document.getElementById(elementId);
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
</script>
</head>
Modify the button code to set the toggle function as an onClick handler for the toggler button.
<body>
<button id="toggler" onclick="toggle(`target`)">TOGGLE</button>
<h2 id="target">THIS HEADER IS ABOUT TO DISAPPEAR!</h2>
</body>
Be careful with the element.style.display = "block" line. The value here is determined by
the HTML element. You may very well want to use inline, flex or grid depending on the
layout of your HTML page.