Events & Hooks

Events

flatpickr features event hooks for the most common and useful actions. For each hook, you may specify a single function, or an array of functions.

After instantiation, all hooks can be accessed via the instance’s config object. Inside the object, all functions are stored in arrays, so you would need to manipulate the array itself to add or remove functions:

Example: instance.config.onChange.push(function() { } );

Each function added to a hook will receive 3 arguments when called. These are:

  • selectedDates - an array of Date objects selected by the user. When there are no dates selected, the array is empty.

  • dateStr - a string representation of the latest selected Date object by the user. The string is formatted as per the dateFormat option.

  • instance - the flatpickr object, containing various methods and properties.

Hooks

onChange

onChange gets triggered when the user selects a date, or changes the time on a selected date.

onOpen

onOpen gets triggered when the calendar is opened.

onClose

onClose gets triggered when the calendar is closed.

onMonthChange

onMonthChange gets triggered when the month is changed, either by the user or programmatically.

onYearChange

onYearChange gets triggered when the year is changed, either by the user or programmatically.

  1. {
  2. onChange: function(selectedDates, dateStr, instance) {
  3. //...
  4. },
  5. onOpen: [
  6. function(selectedDates, dateStr, instance){
  7. //...
  8. },
  9. function(selectedDates, dateStr, instance){
  10. //...
  11. }
  12. ],
  13. onClose: function(selectedDates, dateStr, instance){
  14. // ...
  15. }
  16. }

onReady

onReady gets triggered once the calendar is in a ready state.

onValueUpdate

onValueUpdate gets triggered when the input value is updated with a new date string.

onDayCreate

Take full control of every date cell with theonDayCreate()hook.

  1. {
  2. onDayCreate: function(dObj, dStr, fp, dayElem){
  3. // Utilize dayElem.dateObj, which is the corresponding Date
  4. // dummy logic
  5. if (Math.random() < 0.15)
  6. dayElem.innerHTML += "<span class='event'></span>";
  7. else if (Math.random() > 0.85)
  8. dayElem.innerHTML += "<span class='event busy'></span>";
  9. }
  10. }

Every flatpickr day has relative positioning, which makes it easier to position indicators as we’d like.

  1. .event {
  2. position: absolute;
  3. width: 3px;
  4. height: 3px;
  5. border-radius: 150px;
  6. bottom: 3px;
  7. left: calc(50% - 1.5px);
  8. content: " ";
  9. display: block;
  10. background: #3d8eb9;
  11. }
  12. .event.busy {
  13. background: #f64747;
  14. }