How to show/hide element on click
- Published:
- Updated:
In my opinion, this is the easiest option when you need to show and hide an element by click the same button. For example, this is how I always implement menus for mobile devices.
HTML code of the button and the hidden block.
<a href="javascript:void(0);" onclick="show('hidden');">Click</a>
<div id="hidden">
Hello world!
</div>
CSS code of the hidden block.
#hidden:not(.show){
display:none;
}
JavaScript function.
function show(id){
let element = document.getElementById(id);
if (element.classList.contains('show')) {
element.classList.remove('show');
} else {
element.classList.add('show');
}
}
The principle of operation is very simple. The “show” function checks for the presence of the “show” class in the “hidden” element. If there is no such class, then it is added, and if there is, then it is removed. Depending on the presence of the “show” class in the element, the display parameter changes.