Pickin’ dates

I had the opportunity to trim some code from The Session recently. That���s always a good feeling.

In this case, it was a progressive enhancement pattern that was no longer needed. Kind of like removing a polyfill.

There are a couple of places on the site where you can input a date. This is exactly what input type="date" is for. But when I was making the interface, the support for this type of input was patchy.

So instead the interface used three select dropdowns: one for days, one for months, and one for years. Then I did a bit of feature detection and if the browser supported input type="date", I replaced the three selects with one date input.

It was a little fiddly but it worked.

Fast forward to today and input type="date" is supported across the board. So I threw away the JavaScript and updated the HTML to use date inputs by default. Nice!

I was discussing date inputs recently when I was talking to students in Amsterdam:

They���re given a PDF inheritance-tax form and told to convert it for the web.


That form included dates. The dates were all in the past so the students wanted to be able to set a max value on the datepicker. Ideally that should be done on the server, but it would be nice if you could easily do it in the browser too.

Wouldn���t it be nice if you could specify past dates like this?

Or for future dates:

Alas, no such syntactic sugar exists in HTML so we need to use JavaScript.

This seems like an ideal use-case for HTML web components:

Instead of all-singing, all-dancing web components, it feels a lot more elegant to use web components to augment your existing markup with just enough extra behaviour.


In this case, it would be nice to augment an existing input type="date" element. Something like this:

Here���s the JavaScript that does the augmentation:

customElements.define('input-date-past', class extends HTMLElement { constructor() { super(); } connectedCallback() { this.querySelector('input[type="date"]').setAttribute('max', new Date().toISOString().substring(0,10)); } });

That���s it.

Here���s a CodePen where you can see it in action along with another HTML web component for future dates called, you guessed it, input-date-future.

See the Pen Date input HTML web components by Jeremy Keith (@adactio) on CodePen.

 •  0 comments  •  flag
Share on Twitter
Published on April 11, 2024 04:57
No comments have been added yet.


Jeremy Keith's Blog

Jeremy Keith
Jeremy Keith isn't a Goodreads Author (yet), but they do have a blog, so here are some recent posts imported from their feed.
Follow Jeremy Keith's blog with rss.