Last updated: Mar 4, 2024
Reading time·2 min
To show or hide a form on a button click:
click
event listener to the button element.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <form id="form"> <input type="text" /> <input type="text" /> <input type="text" /> </form> <button id="btn">Toggle form visibility</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const form = document.getElementById('form'); if (form.style.display === 'none') { // 👇️ this SHOWS the form form.style.display = 'block'; } else { // 👇️ this HIDES the form form.style.display = 'none'; } });
style.display
property removes the form from the DOM, if you want to make the form element invisible, but still take up space on the screen, scroll down to the example that uses the style.visibility
property.We added a click
event listener to the button element.
On each click, we check if the form's
display property is set to none
.
If the form is already hidden, we show it by setting its display
property to
block
.
On the other hand, if the form is not hidden, we hide it by setting its
display
property to none
.
We used the display property in the example. However, you might need to use 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 does not exist.On the other hand, when an element's visibility property is set to hidden
, it
still takes up space on the page, however, the element is invisible (not drawn).
The element still affects the layout on your page as normal.
visibility
Here is an example that uses the visibility
property to make the form element
invisible, but still take up space on the page.
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const form = document.getElementById('form'); if (form.style.visibility === 'hidden') { form.style.visibility = 'visible'; } else { form.style.visibility = 'hidden'; } });
Even though the form element is not rendered, it still affects the layout on the page as normal.
When we used the display
property to hide the form element, the button would
take its place in the DOM as the form element got completely removed from the
document.