🛠️ Datepicker: Showing and hiding

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠️ Datepicker: Showing and hiding

We want to hide the Datepicker at first. We only want to show the Datepicker when the user clicks on the <input>.

To hide the Datepicker, we add the hidden attribute to the Datepicker. We’ll do this inside createDatepicker.

const createDatepicker = (input, date) => {
  // ...
  datepicker.innerHTML = /*...*/
  datepicker.setAttribute('hidden')
  // ...
}

When the user clicks on the input element, we want to show the Datepicker. Here, we can either use the click or focus event. We’ll use click for now. (You’ll learn why we need to switch to focus later).

const createDatepicker = (input, date) => {
  // ...
  input.addEventListener('click', event => {
    datepicker.removeAttribute('hidden')
  })
}

Ensuring the Datepicker stays opened

We want to make sure the Datepicker stays opened when:

  1. User clicks inside the Datepicker
  2. User clicks on the <input>

We want to close the Datepicker if the user clicks anywhere else.

To do this, we can attach an event listener to the document.

const createDatepicker = (input, date) => {
  // ...
  document.addEventListener('click', event => {
    // ...
  })
}

If the click event originates within the datepicker, we do nothing.

const createDatepicker = (input, date) => {
  // ...
  document.addEventListener('click', event => {
    if (event.target.closest('.datepicker')) return
  })
}

If the clicked target is the input, we do nothing as well.

const createDatepicker = (input, date) => {
  // ...
  document.addEventListener('click', event => {
    if (event.target.closest('.datepicker')) return
    if (event.target.closest('input') === input) return
  })
}

We’ll hide the datepicker if the event originates elsewhere.

const createDatepicker = (input, date) => {
  // ...
  document.addEventListener('click', event => {
    if (event.target.closest('.datepicker')) return
    if (event.target.closest('input') === input) return
    datepicker.setAttribute('hidden', true)
  })
}

Keeping “focus”

The input’s background turns blueish-grey when we click inside the Datepicker. This hints to users they no longer focusing on the input.

It’s true that they’re no longer focusing on the input, but they’re they’re interacting with the Datepicker. They’re trying to find the correct date! In this case, we can assume they’re still want to keep focus on the <input> element.

Unfortunately, it’s confusing to talk about focus when you haven’t learned how browsers manage focus. So we’ll continue to work on this in the Keyboard module.