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.
function 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).
function 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:
- User clicks inside the Datepicker
- 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.
function createDatepicker(input, date) { // ... document.addEventListener('click', event => { // ... })}If the click event originates within the datepicker, we do nothing.
function 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.
function 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.
function 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.
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson