Search code examples
javascripthtmldatepicker

How to programmatically invoke the native datepicker on a mobile device


I want to programmatically kick off the native datepicker on my web page (that is run on iOS and Android). I know that I can use <input type="date" but that would require user input.

How do I kick it off programmatically?


Solution

  • The web platform now ships with the HTMLInputElement showPicker() method, a canonical way to show a browser picker not only for dates, but also time, color, and files. At the time of writing, showPicker() is available in Chrome 99 or later.

    Calling showPicker() on an element shows a browser picker to the user. It must be called in response to a user gesture such as a touch gesture or mouse click; otherwise it will fail with a NotAllowedError exception. For security reasons, it will throw a SecurityError exception when it's called in a cross-origin iframe.

    A browser picker is shown when the element is one of these types: "date", "month", "week", "time", "datetime-local", "color", or "file".

    The example below shows you how to open a browser date picker.

    <input type="date">
    <button>Show the date picker</button>
    
    <script>
      const button = document.querySelector("button");
      const dateInput = document.querySelector("input");
    
      button.addEventListener("click", () => {
        try {
          dateInput.showPicker();
          // A date picker is shown.
        } catch (error) {
          // Use external library when this fails.
        }
      });
    </script>
    

    A browser picker can also be prepopulated with items from <datalist> or "autocomplete".

    See https://developer.chrome.com/blog/show-picker/ and https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/showPicker