DEV Community

Avnish
Avnish

Posted on

Show an Element if a Checkbox is checked using JavaScript

The difference between using display and visibility to show or hide elements is significant:

  • display: When set to none, the element is completely removed from the document flow. It does not occupy any space on the page.
  • visibility: When set to hidden, the element is not visible, but it still occupies space on the page.

Here’s a breakdown of the examples provided:

1. Using display

This method completely hides or shows the element by modifying its display state.

const checkbox = document.getElementById('show');
const box = document.getElementById('box');

checkbox.addEventListener('click', function handleClick() {
  if (checkbox.checked) {
    box.style.display = 'block'; // Element is shown
  } else {
    box.style.display = 'none';  // Element is hidden
  }
});
Enter fullscreen mode Exit fullscreen mode

HTML Example:

<input type="checkbox" id="show"> Show/Hide Box
<div id="box" style="display: none;">This is a box.</div>
Enter fullscreen mode Exit fullscreen mode

Behavior:

  • When the checkbox is checked, the element appears.
  • When unchecked, the element is removed from the document layout.

2. Using visibility

This method toggles the visibility of the element without affecting the layout.

const checkbox = document.getElementById('show');
const box = document.getElementById('box');

checkbox.addEventListener('click', function handleClick() {
  if (checkbox.checked) {
    box.style.visibility = 'visible'; // Element is visible
  } else {
    box.style.visibility = 'hidden'; // Element is hidden
  }
});
Enter fullscreen mode Exit fullscreen mode

HTML Example:

<input type="checkbox" id="show"> Show/Hide Box
<div id="box" style="visibility: hidden;">This is a box.</div>
Enter fullscreen mode Exit fullscreen mode

Behavior:

  • When the checkbox is checked, the element becomes visible.
  • When unchecked, the element remains in the layout but becomes invisible.

Choosing Between display and visibility

  • Use display if you want to completely hide the element and remove it from the layout.
  • Use visibility if you need the element to remain in its place but not be visible.

Top comments (0)