linkedlist:

Detect whether a Browser has a built-in Date Picker

#9 · · HTML, browser, compatibility

The web is evolving rapidly. But unfortunately, that does not mean that all users have browsers that actually support everything we need. It is thus essential to be able to detect whether a certain browser supports a certain feature. For date pickers, this is not different at all. While most browsers have added support for <input type="date"> years ago, that does not mean that they also have a date picker. Some browsers have one built-in, and for all the others, you need to add your own. So to detect whether a browser offers a date picker, you can use this function.

function hasDatePicker() {
  var input = document.createElement('input');
  input.setAttribute('type', 'date');
  input.value = '2018-01-01';
  return !!input.valueAsDate;
}

That function can be used in browsers and you just need to call it like if (hasDatePicker()) { /* do something */ }. It creates a new input element (without actually adding it to the document DOM) and adds the type="date" attribute. There are a number of things a browser should implement for that date state. But for our detection script, we only use a single attribute that should be defined on the DOM element, namely valueAsDate. The valueAsDate attribute represents the value of the element, interpreted as a date object. That means that we can just set the input value to a valid date string and check whether the valueAsDate is truthy. In browsers that support valueAsDate, it will be equal to new Date('2018-01-01') and everywhere else it is just undefined.

Luckily for us, there (currently) is not a single widespread web browser that has support for valueAsDate but does not have a built-in date picker. It is thus a good way to detect built-in date pickers. As of 2018, all modern browsers like Mozilla Firefox (desktop and mobile), Google Chrome (desktop and mobile), and Microsoft Edge have a date picker built-in. The only exception is, once again, Apple Safari on desktop.