EN
JavaScript - hide and show element on click event
0
points
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>