Code Monkey home page Code Monkey logo

tiny-date-picker's Introduction

Tiny Date Picker

A light-weight date picker with zero dependencies.

  • Zero dependencies
  • Roughly 3.5KB minified and gzipped
  • IE9+
  • Mobile-friendly/responsive
  • Supports multiple languages
  • TinyDatePicker demo

Installation

npm install --save tiny-date-picker

Usage

Include a reference to tiny-date-picker.css and tiny-date-picker.js, or import it import TinyDatePicker from 'tiny-date-picker'; then call it like this:

// Initialize a date picker on the specified input element
TinyDatePicker(document.querySelector('input'));

// Or with a CSS selector
TinyDatePicker('.some-class-or-id-or-whatever');

Documentation

License MIT

Copyright (c) 2015 Chris Davies

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

tiny-date-picker's People

Contributors

alcalyn avatar cameronbraid avatar cedric-legallo avatar chrisdavies avatar ericconstantinides avatar gavynriebau avatar scottishcyclops avatar taomatico avatar tihoho avatar unijad avatar victorvoid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tiny-date-picker's Issues

Parsing dates from different locales

The trouble with only keeping of the string value of the date in state is that JS's parsing is difficult from different locales.

E.g. If my locale is en-GB I display dates as '22/06/2017'. There is not an easy way to parse this into a Date object:

new Date('22/06/2017') // InvalidDate
new Date('10/06/2017') // Fri Oct 06 2017 00:00:00 GMT+0100 (BST) <- Incorrect for my locale

It seems that the date-picker should remember its current date as a date object, and its options (e.g. min, max, preselectedDate) should be passed as date objects and not rely on the parse function to translate themselves.

Callback and focus next

Hi, i love your date picker, use it in 2 projects and some great options you may add to it are:

  • callback - execute something before, while or after a date is selected
  • focus next - usually in a form after you select a date you must fill some other field, so a focus on the next element after selection will help (this can be a data-type attribute on the element itself) so something like this:

<input type="text" class="date-example" tabindex="400" id="MyDate" data-focus_next="MyOtherField" /> <input type="text" id="MyOtherField"/>

Good job!

CSP script-src Violations

Hey Chris,

Absolutely love your project. It provides a great looking date picker out of the box.

However I've just encountered an issue when adding a Content Security Policy to my site. The <a href="javascript:;" is being blocked (as it should) because my policy disallows inline javascript URL execution. Any chance you could change to a non-javascript method of ignoring the <a> tag click events? Maybe an e.preventDefault() in the click handler?

Cheers,

Derek

Selecting Date in IE 11 on Win 7 causes date picker to reappear

This one is a bit tricky.
A colleague can reliably reproduce this on mentioned setup. I have IE 11 on Win 8 in Virtual Box and can not. Looking at the code I can not immediately see any issue there. I could imagine though it has something to do with the input field regaining focus after the date picker closes.

Actual Behavior

  • click in input to pen date picker
  • select date
  • date picker disappears and immediately reappears
    closing via button works, but selecting a date will trigger the same behaviour over and over again

Expected Behaviour

  • click in input to pen date picker
  • select date
  • date picker closes

Modularize and bundle with rollup

I didn't use a bundler at first, just because this started out an experiment in minification optimizations. Now, it's actually being used in production, the code really should be properly factored and modularized and bundled with a good optimizing bundler.

smart positioning

I know there is only "modal" and "below" mode, but "below" is just not good for all the situations, ideally the calendar should be smart about the available space for all directions and position itself properly.

Considering the manual date input is only accommodated by "below" mode calendar, this mode is more desired than modal, because manual input is pretty standard.

Thank you and keep up with the awesome work ๐Ÿ‘

Selected day is also highlighted in other months

Actual
If I select a date in the picker and then reopen it again, moving to a different month shows the same day selected.

Expected
If I change the view to another month and the selected day is not visible, then no day is selected.

Steps to reproduce

  1. Open date picker
  2. Select August 30th
  3. Open date picker again
  4. Change month to September
  5. September 30th is selected

Firefox do not allow month to be changed

When I click on "previous" or "next" month buttons in Firefox date picker closes just as if I used "close" button.

Steps to reproduce:

  1. Open Firefox 46 (also tested on 48 alpha)
  2. Navigate to http://chrisdavies.github.io/tiny-date-picker/
  3. Open date picker
  4. Try changing month to previous / next one

I narrowed down this issue to this line: https://github.com/chrisdavies/tiny-date-picker/blob/master/tiny-date-picker.js#L62

If I get rid of if statement and always call e.preventDefault() then I can change months just fine.

Events don't work on elements without class

The on function uses the RegExp /./ which will match any string of at least one character. So if my <input> element has no class, the handler function doesn't get called. Changing the default RegExp to /.?/ does the trick.

format suggestion. also, a working snippet for angularjs 1.x that handles both mongodb and mysql dates

To support dates coming from databases like mysql or mongodb, the format/parse functions need to be adjusted.

.directive('datePicker',function($parse){

    return {
        restrict: 'A',
        link: function(scope,element,attrs){

            if(attrs.datePickerOptions){
                attrs.$observe('datePickerOptions',function(){
                    link(attrs.datePickerOptions);
                });
            }else{
                link(false);
            }

            function link(options){

                var defaults = {
                    mode: 'dp-below',
                    // Used to convert a date into a string to be used as the value of input. If you specify format,
                    // you must also specify parse. Parse and format are complimentary. Format converts a date to a
                    // string, and parse converts a string to a date.
                    format: function (date) {
                        if(typeof date == 'string'){
                            date = new Date(date);
                        }
                        return date.toLocaleDateString();
                    },

                    // Used to parse a date string and return a date (e.g. parsing the input value)
                    // The value of str can be undefined / null, so you need to handle this case.
                    parse: function (str) {
                        var date = new Date(str);
                        return isNaN(date) ? new Date() : date;
                    }
                };

                var getter = $parse(attrs.ngModel);
                var setter = getter.assign;
                var date = getter(scope);
                setter(scope,defaults.format(date));

                TinyDatePicker( element[0],angular.extend({}, defaults, (options||{})  ));

            }

        }
    };

})

Tabs don't work properly in Safari

When the date picker is shown in Safari, tabbing doesn't select the next button/link in the picker, but instead seems to select the underlying input.

No Modal

Tiny-Date-Picker is awesome. Simple and light weight. Can it be used without a modal, so the calendar is always visible on the page? How should this be done?

Not an issue. Merely a suggestion.

Are you considering adding range-functionality? In my opinion this is the cleanest/ most effective approach: http://longbill.github.io/jquery-date-range-picker. It's similar to Bootstrap's and jQuery UI's sollutions, but it's snappier. The downside: It's jQuery dependent.

This guy made a pure JS variant of the afforementioned range-pickers, but it's a bit too much: http://lopezb.com/hoteldatepicker/

Anyway. If your tiny vanilla JS picker gets a snappy range functionality it will definitely be my go-to picker in the future ;-)

Good work!

Time entry only , no AM or PM

Hi, I have user who just want to enter amount of time worked only, i.e. no AM or PM, i.e. how long and not when for 8HRs, or 14 hrs etc.

I was unable to disable the AM & PM text, can you please share the setting/example to disable it.

Also

  • how to show default hours: for e.g. on select box, default to 08:00 hrs. no AM or PM
  • Different color for HH:MM hours (Blue) and Mins (green)
  • show a button to fill https://github.com/kbwood/timeentry/blob/master/jquery.timeentry.js
    image

thanks

Datepicker sometimes closes itself when selecting a year

When selecting a year, the Datepicker closes itself.

Context:

  • Using Chrome
  • dp-below mode
  • having date input empty
  • years from 1900 to today

Open year selector, it starts from 1900, then select 1905: the datepicker closes itself.

This line is called:

https://github.com/chrisdavies/tiny-date-picker/blob/master/tiny-date-picker.js#L148

document.activeElement contains my <body> element when it closes. When it does not close (expected behaviour), it contains <a tabindex="-1" href="javascript:;" class="dp-day dp-current" data-date="-2145920400000">1</a>

I couldn't reproduce it on demo page.

Including DateRangePicker does not seem to work with Webpack

When I try to import DateRangePicker with Webpack, DateRangePicker will equal an empty object, if I include it "the old fashioned" way via a script tag, it seems to work.

This logs {}:

import DateRangePicker from 'tiny-date-picker/date-range-picker';

document.addEventListener("DOMContentLoaded", function() {
  console.log(DateRangePicker);
});

This logs undefined:

import { DateRangePicker } from 'tiny-date-picker/date-range-picker';

document.addEventListener("DOMContentLoaded", function() {
  console.log(DateRangePicker);
});

This logs just the TinyDatePicker function:

import DateRangePicker from 'tiny-date-picker';

document.addEventListener("DOMContentLoaded", function() {
  console.log(DateRangePicker);
});

This logs an object with TinyDatePicker and DateRangePicker

// script tag with tiny-date-picker in <head>

document.addEventListener("DOMContentLoaded", function() {
  console.log(DateRangePicker);
});

I'm no expert in Webpack or ES6 imports/exports, but I'd be happy to help if you give me some hints as to where this might be happening.

scrollbars appearing after modal activated

Firstly, tiny-date-picker is awesome, I love how nice it looks and how clean your code is.

The only issue I have with it is that, under the following conditions, activating the picker causes vertical scrollbars to show:

  • Use display: flex on body element with flex-direction: column
  • Include a "main" or "content" wrapper with flex: 1
  • Include a second element (e.g. footer)

I was using the above styling to create a content section with a footer.

Took me some time to figure out exactly how to replicate this so I saved these conditions so you can see what I'm talking about:
here
Just click the picker to see the issue (sorry about the butchered styling).

I found this is resolved if line 12 of TinyDatePicker, is changed from:

var focusCatcher = htmlToElement('<button style="position: absolute; width: 1; height: 1; overflow: hidden; border: 0; background: transparent;"></button>');

to (note the extra top: 0 inside the style attribute).

var focusCatcher = htmlToElement('<button style="position: absolute; width: 1; height: 1; overflow: hidden; border: 0; background: transparent; top: 0;"></button>');

Pass an array of dates to be highlighted in the calendar.

Hi.

I am using Tiny Date Picker inside an events booking form. Is it possible to pass an array of dates that can be displayed inside the calendar (with the date being highlighted).

The reason I want to do this is so the customer knows the venue is booked on that certain date.

Thanks

How can i change date format?

Hi, by default date picker format d/m/y like 3/30/2018, how to change date format via option? I want change to Y/m/d?

need ability to access javascript events on control

Is there a way to get standard js events passed into the select event?

I need currentTarget specifically because for my process, I need to grab which specific date control was selected on a page with multiple date controls.

The underscore and 'dp" don't seem to expose all events:

select: (_, dp) =>

Thanks

iOS safari

Hi

Thanks for sharing this fantastic little date picker. Had to make two tiny changes so it would work on iOS 9.35 under Safari.

Issue description:
After clicking on the date input field on stock safari on iOS 9.35 , nothing happens.

Reason:
Appears to be twofold.
First that this version of Safari doesn't like mousedown, but 'touchend' works.
Second, Safari sets context.inputFocused() asynchronously, so it's still 'indefined' when check by TinyDate, preventing the modal from being displayed.

My workaround was just to check for 'touchend' in both places separately and not bother to check if the element is focused (since tab isn't an issue on most touch devices). Works fine then.

Thanks again for sharing this!

Hide or at least disable days not in current month

It would be super helpful if the js can be smart enough to figure out how many extra days from previous/next month is needed to include in current month, 6 from previous month before 1st seems to be not too bad, but 13 days from next month is definitely too much. At least js should be able to tag those not belong to current month so we can do something with the css.

Thank you and love what you doing, keep it up :)

onOpen after format

I used :
format: function (date) { return date.toLocaleDateString(); }

and, for example i have 3/7/2017 (3rd of July 2017) but when i open the calendar , i found 7/3/2017 (7th of March 2017)

expose render function, or inRange callback, or...

Nice job on the date picker. I really like the simplicity.

Seems like a common use case could be to make an ajax call when the year, or month changes to determine which days should be enabled or disabled. Currently, not seeing a great way to do this, although I could just be missing it.

I've exposed the mode render function to the picker. I'm making an ajax call when state changes, updating a cache of available days, re-rendering, and checking the cache in the inRange function. It works, but there's the obvious visual glitch of days showing and then being disabled.

Just wondering 1) if there's any reason not to expose render, and 2) is there a better way to accomplish this maybe something with the inRange function?

Error using pattern atribute

I'm using the "pattern" attribute on an but form whenever I try to submit the form it selects the field again by reopening the modal.

The output was tested against the "pattern" and this ok reopen the modal and consequently does not send.

The "pattern":

<input id="birthday-form-input" type="text" pattern="/^([\d]{4})\/([\d]{2})\/([\d]{2})$/">

Example of output from Tiny Date Picker:

'1999/12/10'

Test in javascript:

/^([\d]{4})\/([\d]{2})\/([\d]{2})$/.test('1999/12/10') // output: true

Complete custom options on Tiny Date Picker instance:

let inputDate = document.getElementById('birthday-form-input');
let datePicker = TinyDatePicker(inputDate, {
    format (dt) {
        return dt.getFullYear() + '/' + (dt.getMonth() + 1) + '/' + dt.getDate();
    },
    parse (dt) {
        if ( !dt ) {
            return new Date();
        }
        const [year, month, day] = dt.split('/').map((s) => parseInt(s, 10));
        const result = new Date();
        result.setYear(year);
        result.setMonth(month);
        result.setDate(day);
        return result;
    },
    max: (function() {
        let date = new Date();
        date.setFullYear(date.getFullYear() -18);
        return ( (date.getFullYear()) + '/' + (date.getMonth() ) + '/' + (date.getDate()) );
    })()
})

How to fix this?

Setting max date to today or date in the past makes `reset` button unusable

Using the max setting to always set the date to today or any date in the past, i.e. max: new Date() makes the reset button unusable.

At least for the today case I tracked this down to be a bug in the inRange method. There, if no date is given, Date.now() is used and compared to the max Date which is always the day at 0:00am. Which means Date.now() is always out of range in this case.

This could be fixed by either setting maxStamp to 23:59:59 or instead of using Date.now() parsing the current day the same as min and max values.

Behaviour is the same for past dates, But I guess the fix is a bit more complicated.

Open modal if you back to tab

Currently, if you open and close modal window and change Chrome tab after, focus still keep on input.
If you back to the tab which contains "date picker", modal view open again because:

on('focus', input, bufferShow);

Chrome emit focus for previews focused element during tab activate.
If "tiny-data-picker" had onClose hook I can be "blur" current focus but, they have not.

IE11 Year Picker issue

Firstly, thanks for the great component guys!

I'm busy with cross browser testing on a project and running into issues with the "year picker" behaviour on IE11 / Windows 10.

To reproduce:

  1. Open http://christophilus.com/tiny-date-picker/ in IE11
  2. Launch the "Example Modal"
  3. Click the year to open the "year picker"
  4. Scroll the list so that the currently selected year (let's say 2017) is out of view
  5. Select a year in the list in front of you
  6. The list "jumps" up so that the previously selected year (2017) is in view again. The new year that was clicked has not been selected and the year picker has not been closed.

One would obviously expect the newly clicked year to be selected, year picker closed, calendar view shown and the year updated to your new selection.

I've tracked down where in the code things are going wrong but not yet been able to fix:

When the new year is clicked, one would expect that onChooseYear() would be executed (https://github.com/chrisdavies/tiny-date-picker/blob/master/dist/tiny-date-picker.js#L570-L575), but this is never called.

The problem (I believe) is in focusCurrent() (https://github.com/chrisdavies/tiny-date-picker/blob/master/dist/tiny-date-picker.js#L852-L855) that is called from the mousedown event handler.

Inside focusCurrent we're placing focus on the originally selected year (2017 in example above) and that seems to be somehow hijacking the click event on the new year's element in IE11 because the list is scrolled so that 2017 is visible in the view again.

You'll notice that, if you don't scroll the originally selected year out of view completely when you're selecting a new year, the selection works fine. I expect this is because IE doesn't have to scroll the original element into view again when it calls focus().

I'll submit a pull request if I find a solution, but please let me know if you have any ideas for solving this.

Bower can't load latest release

Thank you for merging and releasing #8 very quickly.

However, the new release is not available via bower since it relies on github tags/releases.
To grant bower the same access as npm releases should be tagged.

Expose an API so we can edit date, open/close selectors

Once I instanciated a TinyDatePicker, I want to change date or open month menu with JS.

In example, I could do things like:

let datepicker = TinyDatePicker(element, params);

// Manually updating date
datepicker.setYear(1950);

// Event API
datepicker.onSelectYear(function () {
    // Manually open selectors for year or month
    datepicker.openMonthSelector();
});

datepicker.onSelectDay(function () {
    datepicker.close();
});

My first need was to create a birthdate selector, and make it more "fluid".

UX problem, same day number is still selected when changing month

Reproduce it:

  • I set a date in the datepicker, i.e the 15 May 2017
  • I close the datepicker
  • I reopen the datepicker (then the 15 is selected with dp.current, which is fine)
  • I change the month by clicking on <, > or though the month selector, i.e April 2017

Expected result:

I should not see any selected day until I click one of them

Current result:

The 15 April 2017 is selected, then it looks like the date is set to April 15, but is not.

I think it should not be selected to don't forget to select a day and "validate" the date. By leaving it selected, it looks like the date is well changed when I change the month, and I close the datepicker without having changed the date.

max date is pre filled in input

It looks like there is a small issue with min and max dates. If The date field is not populated I would expect it to stay empty even though currentDate is out of range.

It seems like the issue is on line 18. I would try fixing it but I am tied up with other projects unfortunately.

Actual behaviour:
Given the date filed has no input value
When a max date is defined
Then the max date is used as input value

Expected behaviour:
Given the date filed has no input value
When a max date is defined
Then the date field stays empty

Please add manual entry of a date

I would love the option to use the datepicker as a popup and not as a overlay modal, so you can also enter a date manually (preferably with different input formats but without having to use moment). I think it would contribute to overal usability.

Double Tap Required on Date Range Picker

Hello Chris,

I ran into an issue on iphone 6s where I need to double tap a date in order for the event 'statechange' to fire. I thought maybe it was just my project, but when I tested your demo the behavior was the same. Any chance you might have an idea what the cause of this is?

Cheers

error showing year view without date selected

version: "3.1.7"

clicking on the year view without first having a date selected causes the following error

Uncaught TypeError: Cannot read property 'getFullYear' of undefined
    at Object.render$2 [as render] (VM1018 nitro.js:33515)
    at Object.render (VM1018 nitro.js:33711)
    at Object.setState (VM1018 nitro.js:33729)
    at showYearPicker (VM1018 nitro.js:33371)
    at VM1018 nitro.js:33828
    at Array.forEach (<anonymous>)
    at HTMLDivElement.onClick (VM1018 nitro.js:33826)
    at HTMLDivElement.wrapped (VM1018 nitro.js:16953)

Disable days?

Is it possible to disable entire days? For example I need to make a datepicker that does not allow weekends so I would want to disable every Saturday/Sunday in TinyDatePicker.

I tried adding .dp-day-disabled to the days alongside .dp-day but this only changed the styling while still allowing the days to be selected.

Kind of janky in FireFox

It seems to randomly not close properly, hide, or show, etc. Just click around a bit and you'll repro it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.