Vanillajs-datepicker - A vanilla JavaScript remake of bootstrap-datepicker for Bulma and other CSS frameworks

Overview

Vanilla JS Datepicker

A vanilla JavaScript remake of bootstrap-datepicker for Bulma and other CSS frameworks

This package is written from scratch as ECMAScript modules/Sass stylesheets to reproduce similar usability to bootstrap-datepicker.
It can work either standalone or with CSS framework (e.g. Bootstrap, Foundation), but works best with Bulma as it's developed primarily for Bulma.

The package also includes pre-built js/css files for those who like to use it directly on browser.

Features

  • Date picker (input-dropdown, inline), date range picker
  • Keyboard operation support (navigation by arrow keys, editing on input field)
  • i18n support (locales, CSS-based text direction detection)
  • Easily customizable to adapt stylesheet for various CSS frameworks
  • Dependency free
  • Made for modern browsers — no support for IE and Edge Legacy (aka non-Chromium Edge)
    ** If you need to support Edge Legacy, Web Components polyfill will allow this library to run on it.
  • Lightweight (well, relatively…) — 34kB (minified, uncompressed)

Demo

Live Online Demo

Documentation

Online Docs

License

Comments
  • How to import additional languages with webpack?

    How to import additional languages with webpack?

    Hi there, Could anybody please give an example how to import the language dependencies via webpack, too? Am I missing something?

    @import Datepicker from 'path/to/node_modules/vanillajs-datepicker/js/Datepicker.js';
    ==
    import { Datepicker } from 'vanillajs-datepicker';
    
    @import de from 'path/to/node_modules/vanillajs-datepicker/js/i18n/locales/de.js';
    == 
    ???
    

    Thanks in advance and best regards!

    opened by mtness 16
  • How to require the js from node_modules

    How to require the js from node_modules

    Module not found: Error: Can't resolve 'vanillajs-datepicker'

    Typically, when using npm packages; I can simply require them via their namespace. No matter what I try with this project, it cannot find the module. I've also tried the path supplied in the docs. Its a Laravel 6/Bootstrap 4 project. Compiling using Mix.

    Any idea what I am doing wrong?

    opened by dannystaff 9
  • Input field should not lose focus when clicking on picker

    Input field should not lose focus when clicking on picker

    It looks really odd that the input field loses focus for a short moment when you click somewhere on the picker. This seems to be easily fixable:

    1. In file pickerListeners.js add the following function:
      export function onMouseDownPicker(ev) {
        ev.preventDefault();
      }
    
    1. In file Picker.js import also onMouseDownPicker and register it:

         ...
      
         import {
           ...
           onMouseDownPicker
         } from '../events/pickerListeners.js';
      
         ...
      
             registerListeners(datepicker, [
                ...
                [element, 'mousedown', onMouseDownPicker],
                ...
             ]);
      

    @mymth Please let me know what you think of this enhancement. I could prepare a PR if you like.

    opened by xdev1 8
  • minDate not working

    minDate not working

    Hello, Thank you for this great library.

    I do have a minor issue. The minDate doesn't work. I tried to set it to today's date, but all previous dates remain active.

    opened by ThomasAggerholm 8
  • Base support for web components

    Base support for web components

    First, many thanks for this great project. vanillajs-datepicker is remarkably flexible, but you currently cannot really use it with custom elements in shadow DOM. There are two showstoppers:

    1. Option container should not only allow a string vaue but also an HTMLElement instance (as document.querySelector will not find elements in the shadow DOM).

      These lines here: https://github.com/mymth/vanillajs-datepicker/blob/4843b2f8527e0dda08db9d12091796f0e570fce7/js/Datepicker.js#L156-L159
      could be replaced by:

      const container =
          options.container instanceof window.HTMLElement
            ? options.container
            : typeof options.container === 'string'
            ? document.querySelector(options.container)
            : null;
      
        if (container) {
          config.container = container;
        }
      
    2. document.activeElement is not working if a corresponding input element is in shadow DOM. See: https://github.com/mymth/vanillajs-datepicker/blob/4843b2f8527e0dda08db9d12091796f0e570fce7/js/events/otherListeners.js#L7-L9

      Couldn't that just be replaced with the following?

      if (!datepicker.active) {
        return;
      }
      

    Would be extremely great if these two issues could be fixed. Let me know if I shall prepare a PR. TYVMIA.

    opened by xdev1 6
  • Focused day (today) shown monthly

    Focused day (today) shown monthly

    Hello,

    I have a problem with the focused class being added to the current date. When they move from March to April, April 29 becomes active, why? This is not today's date.

    Every month, the 29th of the month has focused class, which in my opinion should only be March. The problem also occurs in the demo: https://raw.githack.com/mymth/vanillajs-datepicker/v1.1.4/demo/

    Can you help me with this?

    opened by gbiorczyk 6
  • Month / Year view : minDate and maxDate blocked

    Month / Year view : minDate and maxDate blocked

    Hey there I recently thrown out all of jQuery / bootstrap of a project and used your plugin as a replacement. Works flawlessly and mostly perfect. Our setup is a daterange picker for different view levels in date, month or year view, so users can live-edit by clicking between their view level.

    One thing we recognized during testing is that when switching to either day or month view the range-dates set by minDate and maxDate are not selectable anymore. I tracked the problem down to the date validation and parsing based on the format.

    What I found out (I do not open a PR but simply describe here as it is quicker for me for the moment):

    In Datepicker.js following lines do check if we are in month / year view. The problem comes when we set new options by the API method setOptions and internly the processOptions / validateDate functions parse the Dates. https://github.com/mymth/vanillajs-datepicker/blob/9de5051545626b116db3d213b0b1e429f296967c/js/Datepicker.js#L36-L59

    What I pass in to the options:

    minDate: "2019-10",
    maxDate: "2021-03",
    format: "yyyy-mm"
    ...
    

    For todays date (2021-03-25), I added a console-log at following position: https://github.com/mymth/vanillajs-datepicker/blob/9de5051545626b116db3d213b0b1e429f296967c/js/options/processOptions.js#L24-L28 retrieving following output dates - time values rewritten in readable format (here only the max-date):

    {
      value: "2021-03",
      format: "yyyy-mm",
      origValue: "2021-03-25"
      returnValue: "2021-03-01"
    }
    

    The return value for the max-date is not useful, as it reflects the beginning of the month, not the ending. What struggles me more is that for the rangeEnd range-check now the maxDate is correctly set to the last day of the month but checked against the first day of the month, which then leads to a blocked selectable month in the picker (when clicking, nothing happens).

    The same problem comes when using year format, the max-range year is not selectable.

    I guess there are now several possible fixes, one way I fixed the problem locally is by modifying the min- and max-date ranges in Datepicker.js (the lines referenced at the beginning) as following:

      let newDates = inputDates.reduce((dates, dt) => {
        let date = parseDate(dt, config.format, config.locale);
        if (date === undefined) {
          return dates;
        }
        let minDate = config.minDate
        let maxDate = config.maxDate
        if (config.pickLevel > 0) {
          // adjust to 1st of the month/Jan 1st of the year
          // or to the last day of the monh/Dec 31st of the year if the datepicker
          // is the range-end picker of a rangepicker
          const dt = new Date(date);
          if (config.pickLevel === 1) {
            // MONTH
            date = rangeEnd
              ? dt.setMonth(dt.getMonth() + 1, 0) // set to last day of month
              : dt.setDate(1); // set to first day of month
          } else {
            // YEAR
            date = rangeEnd
              ? dt.setFullYear(dt.getFullYear() + 1, 0, 0) // set to last day of year
              : dt.setMonth(0, 1); // set to jan 1st
          }
          // We need to also adjust the month / year view for min and max dates
          maxDate = config.pickLevel === 1
            ? (new Date(maxDate)).setMonth(dt.getMonth() + 1, 0) // set to last day of month
            : (new Date(maxDate)).setFullYear(dt.getFullYear() + 1, 0, 0) // set to last day of year
          minDate = config.pickLevel === 1
            ? (new Date(minDate)).setDate(1) // set to first day of month
            : (new Date(minDate)).setMonth(0, 1) // set to jan 1st
        }
    

    By updating the min/max ranges now the isInRange method correctly allows the selection of the upper range month / year, in my example 2021-03.

    Hope this helps. Maybe I open a PR later, but feel free to do it yourself.

    opened by steve-ks 6
  • Not bind to input element

    Not bind to input element

    Is there a way to not bind the component to an input element? I need to open the calendar when user clicks on a div, show the floating calendar positioned absolute with a given (x, y) offset relative to the clicked div then upon selecting a day from the calendar, it needs to update a variable. Also when calendar pops up the selected day should be that of the variable's value.

    Trying to hack it right now by binding to a hidden input but its an ugly solution especially when I don't see a way to control the calendar's positioning. It would be nice if datepicker.show() would accept some parameters to control positioning like this:

    datepicker.show(atElement, {x: 4, y: 15});
    

    Where calendar would be positioned at x, y offset from the location of given element.

    opened by Gruski 6
  • Listening for event from date picker

    Listening for event from date picker

    Please forgive the noob-ness of this question, but I am wondering how I can listen for when a date is selected to call a function. In my case, I wish the page to reload with a new URI using the date when a selection occurs. (window.location.href = urlNew; // where urlNew is generated to include a Date-parameter based on the selected date)

    opened by MrSandvik 5
  • Enhance Datepicker be extensible by users to add custom buttons with user specified dates

    Enhance Datepicker be extensible by users to add custom buttons with user specified dates

    Enhances Datepicker to allow user to extend picker by adding custom buttons with specified dates, like for example Yesterday, Start/End of Quarter, Birthdays :) and many more, user provided dates. Allows users to add more than one button, though not recommanded to have more than 2 for better UX.

    This PR includes the changes to

    1. Datepicker and DateRangepicker API to allow users to add button with label and function that provides the date.
    2. Add implementation in Picker UI and a place holder for these buttons in pickerTemplate and add new quick control template
    3. Add test cases to Datepicker to test new API
    4. Styling to these new buttons, similar styling as Clear/Today button to be consistant with rest of UI
    5. Finally, add them to demo code that demonstrates this new feature

    Potential issues not tested are buttons are diplayed at top when Picker pops up than down; and when user provided function takes long time to return a date (calls a remote server etc.), could degrade the performance of Picker UI. Considering the simple scenarios of user function returns quickly returns outweights these issues, hopefully.

    opened by hsiddanthi 4
  • Add variant behavior for out of range dates

    Add variant behavior for out of range dates

    The current behavior for setting dates which are not within the given minDate maxDate range is to just ignore them. When the datepicker is not used to pick the date but the date is entered by hand there is no feedback about the wrong date. There is no way to display a warning or hint, either. Additionally the state between input element value and the datepicker date(s) diverge and if the selected date is processed through Datepicker#getDate(), the user enters a date which he/she is not aware of. I'm currently thinking of a softer approach which allows to set invalid dates when entering them using the keyboard. In this case, the minDate and maxDate could prevent dates to be picked using the picker. Additionally there could be a small API which allows to check the state (valid/invalid) of the entered dates like Datepicker#isDateValid() or perhaps an event like dateInvalid. The latter could be used e. g. to change the border color or other. What do you think?

    opened by henkesn 4
  • Add ability to disable showing the next or previous dates in month

    Add ability to disable showing the next or previous dates in month

    Will be nice to do something like next:

    {
      ...
      daysOfNextMonth: false,    //  default is true
      daysOfPreviousMonth: false,    //  default is true
      ...
    }
    

    Might be even I can try to implement it. So, what you think?

    opened by loqimean 3
  • recurrence of datesDisabled

    recurrence of datesDisabled

    From my understanding, if one doesn't append the year to a date, then only the current year's is disabled, but if the year is appended then same date of different years doesn't get disabled.

    Is recurrence of disabled dates possible? If not, is it not in the spirit of the plugin to implement this possibility?

    Thank you for this nice plugin.

    opened by mestrini 7
  • Allow approximate dates to be typed in:

    Allow approximate dates to be typed in: "2022-10" and "2022"

    Hello! really appreciate all the hard work you've put into this library!

    I use it for a site where you can visualise your family tree generations back. Because of this, when you go back in time, some dates will be approximate. Maybe you just know the year, or just a year and date. In the backend I support this by allowing both YYYY-MM-DD, YYYY-MM, and YYYY in the same field. I'd like to allow the user to type in those values, no need to support them in the actual picker.

    Problem is, I the datepicker seems to try to parse the year to a full date.

    It looks like I should be able to give a private format option, define a toValue and toDisplay value. But I can't figure out how to reuse all of your wondeful existing logic. I don't want to copy your whole parser, so I was hoping that I could call that existing parser, except for the cases where the format matches YYYY-MM or YYYY...

    Is there someone that reads this that could give some pointers that can help me achieve this?

    My setup is as simple as this:

    var options = {
        format: "yyyy-mm-dd",
        weekStart: 1,
        format: {
            toValue(date, format, locale) {
                ...
            },
            toDisplay(date, format, locale) {
                ...
            },
        },
    };
    var elements = document.querySelectorAll('.date input');
    elements.forEach((elem) => { new Datepicker(elem, options) });
    
    opened by EmilStenstrom 1
  • Add function to set view date.

    Add function to set view date.

    Hi,

    I really like your datepicker. I use it as a meal planner. Each time a user connects, I will look for the dates in a db. But the view is automatically on the last date. I would like the focus to be on today's date.

    Do you think this feature is possible?

    Thanks!

    opened by aydam2728 3
Owner
null
TheDatepicker - Pure JavaScript Datepicker 📅

Pure JavaScript Datepicker by Slevomat.cz.

The Datepicker 27 Dec 16, 2022
A simple and reusable datepicker component for React

React Date Picker A simple and reusable Datepicker component for React (Demo) Installation The package can be installed via npm: npm install react-dat

HackerOne 7k Jan 4, 2023
An easily internationalizable, mobile-friendly datepicker library for the web

react-dates An easily internationalizable, accessible, mobile-friendly datepicker library for the web. Live Playground For examples of the datepicker

Airbnb 12k Jan 6, 2023
A project implementing a datepicker with format dd/MM/yyyy from scratch.

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

José Antônio 2 Jan 11, 2022
A tiny and fast zero-dependency date-picker built with vanilla Javascript and CSS.

A tiny zero-dependency and framework-agnostic date picker that is incredibly easy to use! Compatible with any web UI framework, vanilla JS projects, and even HTML-only projects!

Nezar 1 Jan 22, 2021
jQuery plugin to allow dragging and dropping of elements and sorting of lists and other nested structures.

Drag and Drop Basic jQuery plugin to allow drag and drop: dragging dropping of dragged elements sorting of lists and other nested html structures (ul,

Ole Trenner 12 Aug 26, 2021
CalendarPickerJS - A minimalistic and modern date-picker component/library 🗓️👨🏽‍💻 Written in Vanilla JS

CalendarPickerJS The simple and pretty way to let a user select a day! Supports all major browser. Entirely written in Vanilla JavaScript with no depe

Mathias Picker 15 Dec 6, 2022
Clocklet - An opinionated clock-style vanilla-js timepicker.

An opinionated clock-style vanilla-js timepicker. Demo Features Keyboard and numpad friendly Autocomplete - e.g. "1"->"01:00", "12"->"12:00", "1234"->

31 Jun 7, 2022
Parse, validate, manipulate, and display dates in javascript.

Moment.js A JavaScript date library for parsing, validating, manipulating, and formatting dates. Project Status Moment.js is a legacy project, now in

Moment.js 47.1k Jan 2, 2023
🕑 js-joda is an immutable date and time library for JavaScript.

js-joda is an immutable date and time library for JavaScript. It provides a simple, domain-driven and clean API based on the ISO8601 calendar.

null 1.5k Dec 27, 2022
⏳ Modern JavaScript date utility library ⌛️

date-fns provides the most comprehensive, yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js. ?? Documentation

date-fns 30.6k Dec 29, 2022
lightweight, powerful javascript datetimepicker with no dependencies

flatpickr - javascript datetime picker Motivation Almost every large SPA or project involves date and time input. Browser's native implementations of

flatpickr 15.4k Jan 3, 2023
🍞📅A JavaScript calendar that has everything you need.

A JavaScript schedule calendar that is full featured. Now your service just got the customizable calendar. ?? Table of Contents Collect statistics on

NHN 10.4k Jan 3, 2023
A lightweight javascript timezone library

Isn't it weird how we can do math in our head, but not date math? how many days until the end of the year? what time was it, 11 hours ago? is it lunch

spencer kelly 3.7k Dec 29, 2022
DEPRECATED: Timezone-enabled JavaScript Date object. Uses Olson zoneinfo files for timezone data.

TimezoneJS.Date A timezone-enabled, drop-in replacement for the stock JavaScript Date. The timezoneJS.Date object is API-compatible with JS Date, with

Matthew Eernisse 830 Nov 20, 2022
lightweight, powerful javascript datetimepicker with no dependencies

flatpickr - javascript datetime picker Motivation Almost every large SPA or project involves date and time input. Browser's native implementations of

flatpickr 15.4k Jan 9, 2023
Lightweight and simple JS date formatting and parsing

fecha Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js. NPM npm install fecha --save

Taylor Hakes 2k Jan 5, 2023
⏱ A library for working with dates and times in JS

Luxon Luxon is a library for working with dates and times in JavaScript. DateTime.now().setZone("America/New_York").minus({ weeks: 1 }).endOf("day").t

Moment.js 13.4k Jan 9, 2023
⚡️ Fast parsing, formatting and timezone manipulations for dates

node-cctz CCTZ is a C++ library for translating between absolute and civil times using the rules of a time zone. Install You will need C++11 compatibl

Vsevolod Strukchinsky 59 Oct 3, 2022