Coder Social home page Coder Social logo

nazar-pc / pickmeup Goto Github PK

View Code? Open in Web Editor NEW
616.0 28.0 195.0 886 KB

Really simple, powerful, customizable and lightweight standalone datepicker

License: BSD Zero Clause License

HTML 1.93% JavaScript 75.93% LiveScript 16.03% SCSS 6.11%
datepicker pickmeup javascript

pickmeup's Introduction

⚠️ Project is archived

I have created this library library many years ago and didn't update it in last few years due to not working with frontend anymore.

With that I decided to archive the project.

If you'd like to step in maintaining and modernize the project with the original vision in mind, please reach out via email.

PickMeUp - Really simple, powerful, customizable and lightweight standalone datepicker

No dependencies, single/range/multiple selections, ability to put custom content into dates, very flexible styling and customization abilities.

Written and maintained by Nazar Mokrynskyi with the help of awesome contributors

Based on DatePicker by Stefan Petre

Browser support:

  • IE 10+
  • 2 latest stable versions of Firefox, Chromium, Opera and Edge

If you find this project useful, consider supporting its development on patreon.com/nazarpc, this would help me a lot!

Or if you are representing a company, here is Faircode page.

Getting started

You need only 2 files: dist/pickmeup.min.js and css/pickmeup.css.

The plugin can also be loaded as AMD or CommonJS module.

Then you can apply datepicker to any element:

pickmeup('.date');

Global default options are stored in pickmeup.defaults

They can be redefined during initialization:

pickmeup('.date', {
	format	: 'Y-m-d'
});

or with data-attributes with pmu- prefix:

<div class="date" data-pmu-format="Y-m-d"></div>

Twitter Bootstrap integration

For Twitter Bootstrap integration you do not need to include style file, but you need to include jquery.pickmeup.twitter-bootstrap.js instead, that will read settings of current Bootstrap theme and apply them to PickMeUp, so that it will look similar to native Bootstrap elements.

To apply integrated version use $(...).pickmeup_twitter_bootstrap() plugin for initialization:

$('.date').pickmeup_twitter_bootstrap();

All options and events are the same.

UIkit integration

For UIkit integration you do not need to include style file, but you need to include jquery.pickmeup.uikit.js instead, that will read settings of current UIkit theme and apply them to PickMeUp, so that it will look similar to native UIkit elements.

To apply integrated version use $(...).pickmeup_uikit() plugin for initialization:

$('.date').pickmeup_uikit();

All options and events are the same.

Configuration options

Option Value type Default Description
date array/number/object/string new Date Selected date after initialization. Can be single date string/object or array depending on selection mode
default_date boolean true If false will keep empty value until date selected
current number/object/string date Represents date that will be in the center of rendered calendar, defaults to date option's value
flat boolean false Whatever if the date picker is appended to the element or triggered by an event
first_day 0/1 1 First day of week: 0 - Sunday, 1 - Monday
prev string Previous button content
next string Next button content
mode single/multiple/range single Date selection mode
select_day boolean true Allow or deny days selection
select_month boolean true Allow or deny months selection
select_year boolean true Allow or deny year selection
view days/months/years days View mode after initialization
calendars int 1 Number of calendars, that will be rendered
format string d-m-Y Date format (aAbBCdeHIjklmMpPsSuwyY are supported)
title_format string/function B, Y Date format for calendar title in days view (aAbBCdeHIjklmMpPsSuwyY are supported). If function, must return the full title as a string. The date and locale are provided as parameters.
position top/right/bottom/left/function bottom Date picker's position relative to the triggered element, if function - must return an object with left and top keys and include units
class_name string Class to be added to root datepicker element
hide_on_select boolean false If true - datepicker will be hidden after selection (for range mode allows to select first and last days)
min number/object/string Min date available for selection
max number/object/string Max date available for selection
separator string - Is used for joining separate dates in multiple mode and first/last dates in range mode
locale string en String, that specifies current locale.
locales object see Localization Key-value object, where keys are locales and values contain localized days of week names and months
render function Executed for each day element rendering, takes date argument, allows to select, disable or add class to element
instance_template function (look at source code) Responsible for rendering simple PickMeUp instance with header and days of weeks
instance_content_template function (look at source code) Responsible for rendering instance content container (which contains years, months or days)
Selecting/disabling dates with custom logic

render options might return object with any of following keys:

  • selected: if true - date will be selected
  • disabled: if true - date will be disabled
  • class_name: will be added to class of day element

Example:

var now = new Date;
pickmeup(element, {
    render : function (date) {
        if (date < now) {
            return {disabled : true, class_name : 'date-in-past'};
        }
        return {};
    } 
})

Events callbacks

In PickMeUp events are native DOM events fired on element when pickmeup() was called and always have pickmeup- prefix.

pickmeup-change

Triggered at date change. Example:

pickmeup(element);
element.addEventListener('pickmeup-change', function (e) {
    console.log(e.detail.formatted_date); // New date according to current format
    console.log(e.detail.date);           // New date as Date object
})
pickmeup-show

Triggered at showing. Example:

pickmeup(element);
element.addEventListener('pickmeup-show', function (e) {
    e.preventDefault(); // Showing can be canceled if needed
})
pickmeup-hide

Triggered at hiding. Example:

pickmeup(element);
element.addEventListener('pickmeup-hide', function (e) {
    e.preventDefault(); // Hiding can be canceled if needed
})
pickmeup-fill

Triggered after filling of PickMeUp container with new markup of days, months, years. May be needed for inner datepicker markup editing.

pickmeup(element);
element.addEventListener('pickmeup-fill', function (e) {
    // Do stuff here
})

Methods

Methods allows external control on datepicker

Hide
pickmeup('.date').hide();
Show
pickmeup('.date').show();
Prev
pickmeup('.date').prev();
Next
pickmeup('.date').next();
Get date
pickmeup('.date').get_date(formatted);

formatted - boolean or string (default false)

  • false - Date object
  • true - string formatted in accordance with format option
  • string is used to specify custom format instead if given during initialization
Set date
pickmeup('.date').set_date(new Date);

date - can be single date string/object or array depending on selection mode

Clear multiple selection
pickmeup('.date').clear();
Update datepicker
pickmeup('.date').update();
Destroy datepicker

Destroys PickMeUp instance, removes created markup, restores everything that was changed to original state.

pickmeup('.date').destroy();

Localization

You can add locales to global defaults and then use different locales in particular instance with locale option. Sample object for English language (no need to add, already included in source code):

pickmeup.defaults.locales['en'] = {
	days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	daysMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
	months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
};

Russian:

pickmeup.defaults.locales['ru'] = {
	days: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
	daysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
	daysMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
	months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
	monthsShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек']
};

Other

Current options (for whatever reason) can be accessed as element.__pickmeup.options.

Root pickmeup element can be accessed as element.__pickmeup.element.

Styling

If you want other colors - just change several variables in scss file.

To change size - adjust font-size for root datepicker element, everything will scale nicely.

Contribution

Feel free to create issues and send pull requests, they are highly appreciated!

Before reporting an issue, be so kind to prepare reproducible example on jsfiddle.net, please.

You can start with working demo of latest stable version of PickMeUp: jsfiddle.net/0kg5jL3p

License

Zero-Clause BSD

https://opensource.org/licenses/0BSD

https://tldrlegal.com/license/bsd-0-clause-license

pickmeup's People

Contributors

dependabot[bot] avatar evdevel avatar grahamcampbell avatar hapcoun avatar jastkand avatar jsmolens avatar konfuze avatar matrozov avatar mojereliev avatar multiwebinc avatar nazar-pc avatar raeno avatar unti1x 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pickmeup's Issues

Callbacks only apply to first of original selector

If you use

$('input[type=date]').pickmeup();

all the callbacks get applied to the first selector match. While I'm not sure the following change doesn't have any other affects, changing

options[i] = options[i].bind(this); to $this.bind(options[i]); on https://github.com/nazar-pc/PickMeUp/blob/master/js/jquery.pickmeup.js#L718 fixes it.

This is because you aren't binding the callbacks to the selector, so this always refers to the first matched selector.

Bower

Please create a bower.json and register the package. It's the most common package manager for front-end packages. Would be nice to be able to automatically update PickMeUp.

May 1935

при отображении календаря стоит май 1935 года. не то, чтобы я привиредливая, но можно как-то поставить стартом календаря текущую дату?

Disabled dates + bootstrap

I'm using bootstrap integrated version.
My issue is, I have noticed that disabled dates don't change their appearance compared to normal dates.
So I have changed disabled variable in jquery.pickmeup.twitter-bootstrap.min.js

screenshot from 2015-03-03 21 15 55

because I haven't found "uk-button" class in bootstrap css files.
Please tell if I'm misunderstanding something or there is a problem.

How to trigger in-build callbacks?

For example - I have multiple calendars, one visible at a time and I want to show only one field with inputs.

This is crucial because I have different callbacks for days and month selection.

Disabled dates

Hello, Nazar!
Is it possible to have the ability to disable dates before current date or specified dates?

Обработка даты

Если поле дата имеет формат timestamp или в поле случайно добавлен символ - календарь выводится со значениями NaN.
Добавьте обработку, если не удалось распознать дату - выводить в календаре текущую дату.

Add option 'select day'

Было бы здорово добавить опцию 'select day' (по аналогии с select_month и select_year), например, для случая, когда нужно выбирать только год и месяц

pmu-{next || prev} clicktarget unreachable with icon

using an icon as the prev or next eles prevents the prev and next events from being triggered.

Temp solution:

      $('.pmu-prev .icon, .pmu-next .icon').on('click', function() {
        $(this).closest('.pmu-button').trigger('click');
      });

Selecting a date should set the input to that value

I'm not sure why this is required, but I had to steal your

change: function (formatted) {
        $(this).val(formatted);
    }

from your demo.js file in order for selecting a date to do anything. Why is the default to not actually set input to the date selected?

Кнопка "Сегодня"

Прекрасное решение. А можно добавить кнопку "Сегодня" для выбора текущей даты?

Не отрабатывает событие change при работе с backbonejs

В связке с бекбоне не отрабатывает событие change если на форму уже повешен PickMeUp.

вызов

... 
el:"#statistic_show_phone",
    events:{
        'change #date_end_shp'                      : 'getDate'
    },
    initialize:function(){
         $('#date_end_shp').pickmeup({
            position       : 'right',
            format  : 'd.m.Y',
            hide_on_select : true
        });
...

пролечил jquery.pickmeup.js

...
    (function (prepared_date) {
if ($this.is('input')) {
$this.val(options.mode == 'single' ?    prepared_date[0] : prepared_date[0].join(options.separator));
}
    options.change.apply(this, prepared_date);
        //:FIX: Исправляет несработавшее событие «change»
        $this.trigger("change");
   })(prepareDate(options));
...

Current month changes after click on the 3 calendars view

When you select a date range in 3 calendars view and click on a non-current calendar, the view updates and the month I clicked in becomes the one at the centre. This behaviour confuses users a lot since they need to understand that the month has moved and they need to make the second click in a different month block. Please remove the feature or add an option to avoid month change when clicked on a date.

Когда мы выбираем диапазон дат в виде с 3-мя календарями и жмем не на текущий месяц, календарь обновляется и тот, на который мы нажали, переносится в центр. Такое поведение вводит пользователей в заблуждение, поскольку им необходимо понять, что текущий месяц изменился и второй клик надо делать в другом блоке. Пожалуйста, исправьте подобное поведение либо добавьте опцию для того, чтобы смены активного месяца при клике на дату не происходило.

Показывать календарь для произвольного инпута

Задача: есть инпут, при клике на который показывается календарь с выбором одной даты. Есть кнопка "выбрать диапазон", при клике на которую нужно показывать календарь с выбором диапазона для того же инпута.
Как лучше этого добиться?

Вопрос по multiple календарю

Доброго дня, не могли бы вы помочь в двух вопросах.

  1. как сделать так, что-бы даты выбранные в этом режиме сортировались в инпуте по порядку, независимо от того, в какой последовательности выбирает пользователь.
  2. Как сделать что-бы после выбора не пропадал календарь.
    в идеале надо скрытый инпут и всегда присутствующий календарь.
    пока реализовал так
    $('.cal').pickmeup({
    position : 'bottom',
    mode : 'multiple',
    dateFormat: 'dd.mm.yy',
    min: new Date
    }});
    $('.cal').pickmeup('show');
    $('.cal').pickmeup('clear');

но после выбора даты и потери фокуса на календаре или инпуте - календарь исчезает

January issue

If i pickup date range at «Dates range» calendar in January. It dont activate last day in range (only January :o).

For example i click on «1» and «22»:
cal

Same in Feb:
cal2

Баг при выборе периода

Собственно если hide_on_select: true + mode: 'range', то после второго клика по input сбрасывается в инпуте конечная дата на начальную

Method 'set_date' does not update input value.

I use input field with single date select, and when I use 'set_date' method to set new date, the input value and date picker representation remains the same, while 'get_date' returns the date I have just set.

I found a workaround - to set input value directly and then call 'update' method, but it's a bit inconvenient, as I have to format date before setting input value, while I'd prefer to use native js Date object.

Thank you.

Вопрос по календарю

Подскажите, пожалуйста, как реализовать когда "calendars: 2" чтобы первый календарь был первым, в данный момент первый предыдущий месяц почему-то. Заранее спасибо

Disabling paging when selecting a date

How to disable changing of the current month when using the 3 calendars + range demo?
It happens when you click on left or right month and sometimes is kind of unexpected.

Also can I have my own types of selection? Like quarter picker?

Dynamically change locale

How I can dynamically reload locale? Only .destroy + .pickmeup() again?

В приложении есть необходимость смены языка на лету. В текущей кодовой базе есть возможность перестройки HTML по требованию? Судя по:

if ($this.data('pickmeup-options')) {
  return;
}

нету :) или я плохо искал? воспользовался убиением и последующим воскрешением с прежними параметрами. Но это не очень производительно.

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

invoking clear in range mode

mode: range, between first and second date selected, issue clear.

the next date selected is taken as the second date in the date range rather than the first.

Bootstrap Modal Window

Выбор даты за модальным окном. Вот пример: вставьте только ресурсы: бутстрап js и бутстрап css и плагины js и css. Я вставляю - у меня не взлетает. Времени возится нет с этим фидлом.

z-index

Спасибо за модуль, пригодился.

Только сначала не увидел всплывающий календарь...
решение оказалось таким:
http://joxi.ru/8AnBg5Xf0VyRAO

Возможно, есть смысл добавить его в исходники?

Выбор только даты

Спасибо за отличный плагин!

В проекте календарь используется несколько раз. В некоторых местах не нужно давать пользователю выбирать год, а в некоторых и месяц, только число месяца. Подскажите, как это можно сделать.

Было бы здорово, если бы можно было вообще отключать выбор года и месяца. Иногда понятнее и быстрее пролистать несколько месяцев стрелочками.

Ещё сейчас не очень красиво получается, когда можно листать далеко за пределы доступных дат. Допустим, у нас доступным промежутком указан 2014 год, а листать можно за много лет вперёд и назад, хотя там все даты задисейблены.

Заранее спасибо!

Safari browser error.

There is seems to be an error in Safari (v 5.0.3):
"TypeError: Result of expression 'options[i].bind' [undefined] is not a function."
Calender is not able to load after that.
Error is located here:
"if($.inArray(i,["render","change","before_show","show","hide"])!=-1){options[i]=options[i].bind(this);}"

AddMonths bug

You can't chain-call the addMonths, i.e new Date().addMonths(1).addDays(-1) because addMonths returns undefined.
Those functions should return the result(i.e , not only modify the actual date but also return that date object).

Maybe return this; will help

Небольшой баг с заполненным полем

Если в текстовом поле уже присутствует какой либо текст и при попытке ввода в поле, появляется окно выбора даты с NaN. Решил небольшой правкой кода, сделал проверку в функции show на корректность созданного объекта Date, если некорректен, то присваиваю текущую дату.

Показ в ie8

доброго дня.
підкажіть, будь ласка, як виводити календарний блок в іе8. На даний момент він просто відсутній.

Input not updating with selected date

I'm using this in a rails application and initializing it on all date inputs with:

$('[type=date]').pickmeup();

but when the date drops down and I select a date, it fails to update the input. It's like my clicks are just ignored

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.