Show an Element if Checkbox is checked using JavaScript #
To show an element if a checkbox is checked:
- Add a
click
event listener to the checkbox. - Check if the checkbox is checked.
- If it is, set the
display
property of the hidden element toblock
.
Here is the HTML for the examples in this article.
Copied!
DOCTYPE html> #box { display: none; width: 100px; height: 100px; background-color: salmon; color: white; } Select an option: Show div Box is now shown
And here is the related JavaScript.
Copied!
const checkbox = document.getElementById['show']; const box = document.getElementById['box']; checkbox.addEventListener['click', function handleClick[] { if [checkbox.checked] { box.style.display = 'block'; } else { box.style.display = 'none'; } }];
We added a click
event listener to the checkbox.
Every time the checkbox is clicked, the handleClick
function is invoked.
In
the function, we check if the checkbox is checked and if it is, we set thedisplay
property of the div
element to block
to show it.
If you uncheck the checkbox, the div's display
property is set to none
and the element is hidden.
We used the display property in the examples, however you might need to use the visibility property depending on your use case.
When an element's display
property is set to none
, the element is removed from the DOM and has no effect on 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,
however the element is invisible [not drawn]. The element still affects the layout on your page as normal.
Here is an example that uses the visibility
property to show an element if a checkbox is checked.
Copied!
DOCTYPE html> #box { visibility: hidden; width: 100px; height: 100px; background-color: salmon; color: white; } Select an option: Show div Box is now shown More content here
And here is the related JavaScript.
Copied!
const checkbox = document.getElementById['show']; const box = document.getElementById['box']; checkbox.addEventListener['click', function handleClick[] { if [checkbox.checked] { box.style.visibility = 'visible'; } else { box.style.visibility = 'hidden'; } }];
If you load the page, you'll see that the element takes up space even when it's hidden.
Even though the element is invisible, it still affects the layout of the page as normal.
Had we set the element's display
property to none
, it would be taken out of the DOM and the next element would take it's place on the page.
Using the display
property to show or hide an element shifts the content on the page, which can be confusing and should be avoided when possible.