Календарь для выбора дат javascript

Date Range Picker

A JavaScript component for choosing date ranges, dates and times.

Originally created for reports at Improvely, the Date Range Picker can be attached to any webpage element to pop up two calendars for selecting dates, times, or predefined ranges like «Last 30 Days».

Getting Started

To get started, include jQuery, Moment.js and Date Range Picker’s files in your webpage:

Then attach a date range picker to whatever you want to trigger it:

You can customize Date Range Picker with options, and get notified when the user chooses new dates by providing a callback function.

Examples

Simple Date Range Picker With a Callback

Date Range Picker With Times

Single Date Picker

Predefined Date Ranges

Input Initially Empty

Options

  • startDate (Date or string) The beginning date of the initially selected date range. If you provide a string, it must match the date format string set in your locale setting.
  • endDate : (Date or string) The end date of the initially selected date range.
  • minDate : (Date or string) The earliest date a user may select.
  • maxDate : (Date or string) The latest date a user may select.
  • maxSpan : (object) The maximum span between the selected start and end dates. Check off maxSpan in the configuration generator for an example of how to use this. You can provide any object the moment library would let you add to a date.
  • showDropdowns : (true/false) Show year and month select boxes above calendars to jump to a specific month and year.
  • minYear : (number) The minimum year shown in the dropdowns when showDropdowns is set to true.
  • maxYear : (number) The maximum year shown in the dropdowns when showDropdowns is set to true.
  • showWeekNumbers : (true/false) Show localized week numbers at the start of each week on the calendars.
  • showISOWeekNumbers : (true/false) Show ISO week numbers at the start of each week on the calendars.
  • timePicker : (true/false) Adds select boxes to choose times in addition to dates.
  • timePickerIncrement : (number) Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30).
  • timePicker24Hour : (true/false) Use 24-hour instead of 12-hour times, removing the AM/PM selection.
  • timePickerSeconds : (true/false) Show seconds in the timePicker.
  • ranges : (object) Set predefined date ranges the user can select from. Each key is the label for the range, and its value an array with two dates representing the bounds of the range. Click ranges in the configuration generator for examples.
  • showCustomRangeLabel : (true/false) Displays «Custom Range» at the end of the list of predefined ranges, when the ranges option is used. This option will be highlighted whenever the current date range selection does not match one of the predefined ranges. Clicking it will display the calendars to select a new range.
  • alwaysShowCalendars : (true/false) Normally, if you use the ranges option to specify pre-defined date ranges, calendars for choosing a custom date range are not shown until the user clicks «Custom Range». When this option is set to true, the calendars for choosing a custom date range are always shown instead.
  • opens : (‘left’/’right’/’center’) Whether the picker appears aligned to the left, to the right, or centered under the HTML element it’s attached to.
  • drops : (‘down’/’up’/’auto’) Whether the picker appears below (default) or above the HTML element it’s attached to.
  • buttonClasses : (string) CSS class names that will be added to both the apply and cancel buttons.
  • applyButtonClasses : (string) CSS class names that will be added only to the apply button.
  • cancelButtonClasses : (string) CSS class names that will be added only to the cancel button.
  • locale : (object) Allows you to provide localized strings for buttons and labels, customize the date format, and change the first day of week for the calendars. Check off locale in the configuration generator to see how to customize these options.
  • singleDatePicker : (true/false) Show only a single calendar to choose one date, instead of a range picker with two calendars. The start and end dates provided to your callback will be the same single date chosen.
  • autoApply : (true/false) Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates are clicked.
  • linkedCalendars : (true/false) When enabled, the two calendars displayed will always be for two sequential months (i.e. January and February), and both will be advanced when clicking the left or right arrows above the calendars. When disabled, the two calendars can be individually advanced and display any month/year.
  • isInvalidDate : (function) A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not.
  • isCustomDate : (function) A function that is passed each date in the two calendars before they are displayed, and may return a string or array of CSS class names to apply to that date’s calendar cell.
  • autoUpdateInput : (true/false) Indicates whether the date range picker should automatically update the value of the element it’s attached to at initialization and when the selected dates change.
  • parentEl : (string) jQuery selector of the parent element that the date range picker will be added to, if not provided this will be ‘body’
Читайте также:  Html тег text color

Methods

You can programmatically update the startDate and endDate in the picker using the setStartDate and setEndDate methods. You can access the Date Range Picker object and its functions and properties through data properties of the element you attached it to.

  • setStartDate(Date or string) : Sets the date range picker’s currently selected start date to the provided date
  • setEndDate(Date or string) : Sets the date range picker’s currently selected end date to the provided date

Events

Several events are triggered on the element you attach the picker to, which you can listen for.

  • show.daterangepicker : Triggered when the picker is shown
  • hide.daterangepicker : Triggered when the picker is hidden
  • showCalendar.daterangepicker : Triggered when the calendar(s) are shown
  • hideCalendar.daterangepicker : Triggered when the calendar(s) are hidden
  • apply.daterangepicker : Triggered when the apply button is clicked, or when a predefined range is clicked
  • cancel.daterangepicker : Triggered when the cancel button is clicked

Some applications need a «clear» instead of a «cancel» functionality, which can be achieved by changing the button label and watching for the cancel event:

While passing in a callback to the constructor is the easiest way to listen for changes in the selected date range, you can also do something every time the apply button is clicked even if the selection hasn’t changed:

Configuration Generator

Источник

Примеры

На этой странице собраны небольшие примеры того, как работает и на что способен Air Datepicker.

Базовые примеры

С опциями по умолчанию

Статичный календарь

Для того, чтобы календарь был постоянно видимый, нужно его проинициализировать не на текстовом поле, или передать параметр

new AirDatepicker('#div'); // Or init with on or elements new AirDatepicker('#input', < inline: true >) 

Выбор даты при инициализации

Для выбора даты используйте опцию selectedDates . На принимает массив дат, строк или чисел. Подробнее можно ознакомится в разделе документации. Давайте выберем сегодняшнюю дату.

Выбор месяца

Для возможности выбора только месяца без конкретного числа, можно использовать комбинацию из опций view и minView — с помощью первой мы устанавливаем текущее представление календаря, а с помощью второй задаем минимально возможное представление.

Режим для мобильных устройств

У Air Datepicker есть режим, который позволяет открывать календарь как модальное окно — в этом режиме он появляется по центру экрана в немного увеличенных размерах для облегчения выбора даты.

Позиционирование

Позиция календаря задается с помощью параметра position — он может быть как строкой так и функцией.

Простое позиционирование

Базовое позиционирование задается через строку — «‘основная ось ‘второстепенная ось'» . Например, покажем календарь справа от текстового поля:

Использование Popper.js

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

В следующем примере обработаем позицию с помощью библиотеки Popper.js. Попробуйте проскролить страницу дальше.

import AirDatepicker from 'air-datepicker'; import from '@popperjs/core'; new AirDatepicker('#el', < container: '#scroll-container', visible: true, position() < let popper = createPopper($target, $datepicker, < placement: 'top', modifiers: [ < name: 'flip', options: < padding: < top: 64 >> >, < name: 'offset', options: < offset: [0, 20] >>, < name: 'arrow', options: < element: $pointer >> ] >) /* Возвращаем функцию, которая вызывается при срабатывании `hide()`, она обязательно должна вызвать функцию `done()` для завершения процесса скрытия календаря */ return function completeHide() < popper.destroy(); done(); >> >) 

При использовании Popper.js, Air Datepicker автоматически повернет указатель в нужном направлении! 😎

Создание анимации появления и скрытия

Air Datepicker позволяет добавить свои анимации появления и скрытия. Вы также можете сделать это своими руками или же использовать любую библиотеку для анимаций.

Для следующего примера возьмем библиотеку anime.js и объединим ее с Popper.js

import AirDatepicker from 'air-datepicker'; import from '@popperjs/core'; import anime from 'animejs'; new AirDatepicker('#el', < position() < let popper = createPopper($target, $datepicker, < placement: 'bottom', onFirstUpdate: state =>< !isViewChange && anime.remove($datepicker); $datepicker.style.transformOrigin = 'center top'; !isViewChange && anime(< targets: $datepicker, opacity: [0, 1], rotateX: [-90, 0], easing: 'spring(1.3, 80, 5, 0)', >) >, modifiers: [ < name: 'offset', options: < offset: [0, 10] >>, < name: 'arrow', options: < element: $pointer, >>, < name: 'computeStyles', options: < gpuAcceleration: false, >, >, ] >); return () => < anime(< targets: $datepicker, opacity: 0, rotateX: -90, duration: 300, easing: 'easeOutCubic' >).finished.then(() => < popper.destroy(); done(); >) > >> ) 

Диапазон дат

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

Минимальная и максимальные даты

Для манипуляции с минимально возможной и максимально возможной датой используйте опции minDate и maxDate . В сочетании с функцией update() можно реализовать выбор дат только в ограниченном диапазоне.

let dpMin, dpMax; dpMin = new AirDatepicker('#el1', < onSelect() < dpMax.update(< minDate: date >) > >) dpMax = new AirDatepicker('#el2', < onSelect() < dpMin.update(< maxDate: date >) > >) 

Выбор времени

Передайте для выбора времени. По умолчанию устанавливается текущее время пользователя. Стартовое значение даты и времени можно регулировать с помощью параметра startDate .

Формат времени

Формат времени задается в объекте локализации или в опции . Для отображения времени в 12-ти часовом варианте, используйте символы ‘h’ или ‘hh’ . Чтобы отобразить период дня добавьте ‘aa’ или ‘AA’ .

Настройка часов и минут

Время регулируется несколькими опциями, это minHours, maxHours, minMinutes, maxMinutes . Также можно настраивать шаг шкалы выбора времени с помощью hoursStep, minutesStep .

Давайте попробуем ограничивать выбор часов с 8 до 19 и добавить шаг выбора минут в значение 5.

Содержимое ячеек

Air Datepicker позволяет изменять содержимое ячеек как угодно. Содержание, классы и статус (активный/не доступный для выбора) регулируются с помощью опции ) => <>)> .

В следующем примере заменим содержимое ячеек из списка дат на произвольную эмоджи, плюс поменяем активный цвет фона таких ячеек

let today = new Date(); new AirDatepicker('#inline-div', < // Handle render process onRenderCell() < let dates = [1, 5, 7, 10, 15, 20, 25], emoji = ['💕', '😃', '🍙', '🍣', '🍻', '🎉', '🥁'], isDay = cellType === 'day', _date = date.getDate(), shouldChangeContent = isDay && dates.includes(_date), randomEmoji = emoji[Math.floor(Math.random() * emoji.length)]; return < html: shouldChangeContent ? randomEmoji : undefined, classes: shouldChangeContent ? '-emoji-cell-' : undefined, attrs: < title: shouldChangeContent ? randomEmoji : '' >> >, // Select 10th day of the month selectedDates: new Date(today.getFullYear(), today.getMonth(), 10) >); 

Изменение заголовков

В Air Datepicker есть возможность изменять подписи в навигации календаря. Можно использовать как статические варианты, так и динамические — передав функцию в соответствующую опцию. Вы можете использовать как html тэги, так и специальные токены для форматирования их в дату.

Статичный заголовок

Динамический заголовок

new AirDatepicker('#el', < navTitles: < days(dp) < if (dp.selectedDates.length) < let date = dp.selectedDates[0]; return `Вы выбрали $ `; > return 'Выберите дату'; > > >)

Добавление кнопок

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

Предустановленные кнопки

Для добавления кнопок воспользуйтесь опцией buttons — она принимает массив строк или массив объектов с описанием кнопки.

Создание своих кнопок

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

new AirDatepicker('#el', < buttons: [ < content(dp) < return dp.opts.timepicker ? 'Выключить выбор времени' : 'Включить выбор времени' >, onClick(dp) < let viewDate = dp.viewDate; let today = new Date(); // Since timepicker takes initial time from 'viewDate', set up time here, // otherwise time will be equal to 00:00 if user navigated through datepicker viewDate.setHours(today.getHours()); viewDate.setMinutes(today.getMinutes()); dp.update(< timepicker: !dp.opts.timepicker, viewDate >) > > ] >)

Источник

Оцените статью