Minimal Clean Date Picker For Input Field – noUiDatePicker

Category: Date & Time , Javascript | May 17, 2017
Author: leongersen
Views Total: 955
Official Page: Go to website
Last Update: May 17, 2017
License: MIT

Preview:

Minimal Clean Date Picker For Input Field – noUiDatePicker

Description:

noUiDatePicker is a minimal vanilla JavaScript date pick that enables the users easily select a date from a specific date range.

How to use it:

Add the following JavaScript and CSS files to the webpage.

<link href="picker.css" rel="stylesheet">
<script src="picker.js"></script>

Create the html for the date picker input. You’re allowed to specify the date range using ‘min’ and ‘max’ attributes:

<input class="date-input-native" id="date" type="date" name="date" min="2016-11-03" max="2017-02-11">
<input class="date-input-fallback" id="alt" type="text" placeholder="Pick A Date">
<div id="picker" hidden></div>

The JavaScript to activate the date picker.

(function(){

  'use strict';

  var dayNamesShort = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
  var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  var icon = '<svg viewBox="0 0 512 512"><polygon points="268.395,256 134.559,121.521 206.422,50 411.441,256 206.422,462 134.559,390.477 "/></svg>';

  var root = document.getElementById('picker');
  var dateInput = document.getElementById('date');
  var altInput = document.getElementById('alt');
  var doc = document.documentElement;

  function format ( dt ) {
    return Picker.prototype.pad(dt.getDate()) + ' ' + monthNames[dt.getMonth()].slice(0,3) + ' ' + dt.getFullYear();
  }

  function show ( ) {
    root.removeAttribute('hidden');
  }

  function hide ( ) {
    root.setAttribute('hidden', '');
    doc.removeEventListener('click', hide);
  }

  function onSelectHandler ( ) {

    var value = this.get();

    if ( value.start ) {
      dateInput.value = value.start.Ymd();
      altInput.value = format(value.start);
      hide();
    }
  }

  var picker = new Picker(root, {
    min: new Date(dateInput.min),
    max: new Date(dateInput.max),
    icon: icon,
    twoCalendars: false,
    dayNamesShort: dayNamesShort,
    monthNames: monthNames,
    onSelect: onSelectHandler
  });

  root.parentElement.addEventListener('click', function ( e ) { e.stopPropagation(); });

  dateInput.addEventListener('change', function ( ) {

    if ( dateInput.value ) {
      picker.select(new Date(dateInput.value));
    } else {
      picker.clear();
    }
  });

  altInput.addEventListener('focus', function ( ) {
    altInput.blur();
    show();
    doc.addEventListener('click', hide, false);
  });

}());