Last updated: Mar 5, 2024
Reading timeยท3 min

To hide a button after clicking it:
click event listener to the button.style.display property to none.display property is set to none, the element is removed from the
DOM.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div id="box" style=" height: 100px; width: 100px; background-color: salmon; display: none; " > Box </div> <button id="btn">Click me</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { // ๐๏ธ hide button btn.style.display = 'none'; // ๐๏ธ show div const box = document.getElementById('box'); box.style.display = 'block'; });

We added a click event listener to the button, so a function is invoked every
time it's clicked.
Each time the button is clicked, its display property is set to none to hide
it.
display property of a div to block to show it after hiding the button.If you click on the button, you'll see the button disappear and the div get
shown.
We set the button's display CSS property
to none to hide it.
visibilityHowever, you might need the visibility property depending on your use case.
display property is set to none, the element is removed from the DOM and does not affect the layout. The document is rendered as though the element doesn't exist.On the other hand, when an element's visibility property is set to hidden,
it still takes up space on the page, but the element is invisible (not drawn).
The element still affects the layout on the page as normal.
Here is an example that uses the visibility property to hide a button after
clicking it and to show a div element.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style=" height: 100px; width: 100px; background-color: salmon; visibility: hidden; " > Box </div> <button id="btn">Click me</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { // ๐๏ธ hide button (still takes up space on the page) btn.style.visibility = 'hidden'; // ๐๏ธ show div const box = document.getElementById('box'); box.style.visibility = 'visible'; });

If you refresh the page, you'll see that the button still takes up space, but is invisible.
This is the difference between setting visibility to hidden and display to
none.
This behavior might be better if you're looking to avoid shifting the layout of the page which might be confusing to users.
You can learn more about the related topics by checking out the following tutorials: