We want to do two things when a user clicks a date in the date grid:
- Highlight the selected date on the Datepicker
- Format and output the selected date to the input field
Highlighting the selected date
First, we need to add an event listener to the date grid. (Weโll use the event delegation pattern as usual). This event listener needs to be in createDatepicker
function createDatepicker(date) { // ...
const dategrid = datepicker.querySelector('.datepicker__date-grid') dategrid.addEventListener('click', event => { // ... })
// ...}We only want to do things if the user clicks on a date (which is a <button> element.
dategrid.addEventListener('click', event => { if (!event.target.matches('button')) return})We can add the is-selected class to highlight the clicked date.
dategrid.addEventListener('click', event => { if (!event.target.matches('button')) return const button = event.target button.classList.add('is-selected')})And weโll remove the is-selected class from other dates.
dategrid.addEventListener('click', event => { if (!event.target.matches('button')) return const button = event.target const buttons = [...button.parentElement.children]
// Showing the selected class buttons.forEach(button => button.classList.remove('is-selected')) button.classList.add('is-selected')})
Showing the selected date in the input field
To show the selected date in the input field, we have to:
- Figure out what date is selected
- Formate the date for output
- Display the formatted date in the input field
Figuring out what date is selected
Each date in the dategrid contains a <time> element. You can look at the datetime attribute to get the selected date.
dategrid.addEventListener('click', event => { // ...
const time = button.firstElementChild const datetime = time.getAttribute('datetime') const selectedDate = new Date(datetime)})Once again, we should not create dates with a date string. Things can break easily. We should create dates with the arguments approach.
To create a date with the argument approach, we can use the datetimeToDate function. But we need to edit datetimeToDate to work with date strings that contain days.
Hereโs what we have written for datetimeToDate:
function datetimeToDate(datetime) { const [year, month] = datetime.split('-').map(num => parseInt(num))
return new Date(year, month - 1)}If we pass in a datetime value that is written in YYYY-MM-DD, we can use split to get year, month and day.
function datetimeToDate(datetime) { const [year, month, day] = datetime.split('-').map(num => parseInt(num))
console.log(year) // 2019 console.log(month) // 2 console.log(day) // 5 // ...}
datetimeToDate('2019-02-05')We can use these values directly in new Date.
function datetimeToDate(datetime) { const [year, month, day] = datetime.split('-').map(num => parseInt(num))
// Remember, `month` needs to be zero-indexed return new Date(year, month - 1, day)}At this point, if you passed in a YYYY-MM format, datetimeToDate would break.
console.log(datetimeToDate('2019-02')) // Invalid Dateconsole.log(datetimeToDate('2019-02-03')) // February 3rd, 2019This happens because day is undefined. We cannot pass undefined into new Date. There are a couple of ways to fix this.
One way is to return a Date with day only if thereโs a day value.
function datetimeToDate(datetime) { const [year, month, day] = datetime.split('-').map(num => parseInt(num))
return day ? new Date(year, month - 1, day) : new Date(year, month - 1)}Another way is to set the default value for day to 1.
function datetimeToDate(datetime) { const [year, month, day = 1] = datetime.split('-').map(num => parseInt(num))
return new Date(year, month - 1, day)}Both methods do the same thing. Weโll use the second one since itโs shorter and cleaner.
Using the new datetimeToDate:
dategrid.addEventListener('click', event => { // ...
const time = button.firstElementChild const datetime = time.getAttribute('datetime') const selectedDate = datetimeToDate(datetime) console.log(selectedDate)})
Formatting the output
The input field requires a date written in DD/MM/YYYY. We can:
- Get
DDwithgetDate. - Get
MMwithgetMonth(but we have to add 1 to this value). - Get
YYYYwithgetFullYear.
dategrid.addEventListener('click', event => { // ...
const selectedDate = datetimeToDate(datetime) const year = selectedDate.getFullYear() const month = selectedDate.getMonth() + 1 const day = selectedDate.getDate()})And we can create the required output format with a template string.
dategrid.addEventListener('click', event => { // ...
const formatted = `${day}/${month}/${year}` console.log(formatted)})
Pay attention to the console. Notice formatted gives you single digit numbers (whenever possible) for days and months? We wanted DD/MM/YYYY, so we need a two-digit string!
We can use toTwoDigitString to convert day and month into two-digit strings.
dategrid.addEventListener('click', event => { // ...
const year = selectedDate.getFullYear() const month = toTwoDigitString(selectedDate.getMonth() + 1) const day = toTwoDigitString(selectedDate.getDate())
const formatted = `${day}/${month}/${year}` console.log(formatted)})
Displaying the formatted date
The datepicker needs to know where to display the formatted date. This means createDatepicker needs to take in the input field as an argument.
Letโs call this second argument input
const date = new Date(2019, 1, 13)const form = document.querySelector('form')const input = form.querySelector('input')
// ...
function createDatepicker(input, date) { // ...}
// ...form.appendChild(createDatepicker(input, date))To output the date, we simply change the inputโs value.
dategrid.addEventListener('click', event => { // ...
const formatted = `${day}/${month}/${year}` input.value = formatted})The input gets updated when the user clicks on a date. But the browser refreshes since we put the Datepicker in a <form>.
This is because buttons inside a <form> sometimes gets treated as submit buttons. In this case, our buttons arenโt submit buttons. We can tell browsers theyโre just buttons by setting type to button.
const previousNextMonthButtons = ` <div class="datepicker__buttons"> <button type="button" class="datepicker__previous"> ... </button> <button type="button" class="datepicker__next"> ... </button> </div>`function createDateGridHTML(date) { // ... for (let day = 1; day <= daysInMonth; day++) { const button = document.createElement('button') button.setAttribute('type', 'button') // ... } // ...}This fixes the refresh problem.
And weโre done!
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