Pikaday - Documentation

Getting Started

Installation

Pikaday can be installed via several methods:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.11.0/css/pikaday.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.11.0/pikaday.min.js"></script>
npm install pikaday

Then, import it into your project (you’ll need a module bundler like Webpack or Parcel):

import Pikaday from 'pikaday';
import 'pikaday/css/pikaday.css'; 
bower install pikaday

Remember to include the CSS file in your HTML <head> for styling.

Basic Usage

Once Pikaday is installed, creating a datepicker is straightforward. You’ll need an input element in your HTML to which the datepicker will be attached. Then, you instantiate a new Pikaday object, passing the input element as a configuration option.

const picker = new Pikaday({
  field: document.getElementById('my-datepicker')
});

This creates a datepicker linked to the input element with the ID “my-datepicker”. Further configuration options allow for customization (see the full documentation for details).

First Example

Here’s a complete example demonstrating a basic Pikaday integration:

<!DOCTYPE html>
<html>
<head>
  <title>Pikaday Example</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.11.0/css/pikaday.min.css">
</head>
<body>

  <input type="text" id="my-datepicker">

  <script src="https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.11.0/pikaday.min.js"></script>
  <script>
    const picker = new Pikaday({
      field: document.getElementById('my-datepicker')
    });
  </script>
</body>
</html>

This code includes the necessary CSS and JavaScript files from a CDN, creates an input field, and then instantiates a Pikaday picker linked to that field. This will produce a simple datepicker allowing users to select a date. Remember to replace the CDN links with your local paths if you’ve installed Pikaday using npm or Bower.

Configuration Options

Pikaday offers a wide array of configuration options to customize its behavior and appearance. These options are passed as a JavaScript object when creating a new Pikaday instance.

field

(Type: HTMLElement | string) The input element or its ID to which the datepicker will be attached. This is a required option. If you provide a string, Pikaday will attempt to find an element with that ID.

const picker = new Pikaday({
  field: document.getElementById('myDate') // Or  field: '#myDate'
});

format

(Type: string, Default: YYYY-MM-DD) The date format to use for display and parsing. Uses Moment.js format tokens (e.g., YYYY, MM, DD, dddd, etc.).

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  format: 'DD.MM.YYYY'
});

formatStrict

(Type: boolean, Default: false) If true, the entered date must strictly match the specified format. Otherwise, lenient parsing is used.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  format: 'YYYY-MM-DD',
  formatStrict: true
});

i18n

(Type: Object, Default: English locale) An object containing localization strings for the datepicker. See the documentation for the structure of this object and available locales.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  i18n: {
    previousMonth : 'Vorheriger Monat',
    nextMonth     : 'Nächster Monat',
    months        : ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
    weekdays      : ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
    weekdaysShort : ['So','Mo','Di','Mi','Do','Fr','Sa']
  }
});

firstDay

(Type: number, Default: 0 (Sunday)) The day of the week to start the week (0 for Sunday, 1 for Monday, etc.).

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  firstDay: 1 // Start week on Monday
});

minDate

(Type: Date) The earliest selectable date.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  minDate: new Date() // Today is the minimum selectable date
});

maxDate

(Type: Date) The latest selectable date.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  maxDate: new Date(2024, 11, 31) // December 31, 2024 is the maximum
});

yearRange

(Type: number | string, Default: 10) The number of years to display above and below the current year. Can also be a string in the format start:end (e.g., 1900:2020).

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  yearRange: 20 // 20 years above and below the current year.  Or yearRange: '1990:2030'
});

bound

(Type: boolean, Default: true) If false, prevents the datepicker from being automatically positioned relative to the input field. Useful for manual positioning.

disableWeekends

(Type: boolean, Default: false) Disables weekend days (Saturday and Sunday).

const picker = new Pikaday({
    field: document.getElementById('myDate'),
    disableWeekends: true
});

disableDayFn

(Type: function(Date), Default: null) A function that determines whether a specific date should be disabled. The function receives a Date object as an argument and should return true to disable the date, false otherwise.

const picker = new Pikaday({
    field: document.getElementById('myDate'),
    disableDayFn: function(date) {
        return date.getDay() === 0 || date.getDay() === 6; // Disable weekends
    }
});

setDefaultDate

(Type: Date) Sets a default date for the picker.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  setDefaultDate: new Date(2024, 0, 1) // Set default to January 1st, 2024
});

setDefaultTime

(Type: Date) Sets a default time (hours, minutes, seconds) for the picker. Note that the default date will also affect the picker’s time.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  setDefaultTime: new Date(0,0,0,14,30,0) //Set default to 2:30 PM
});

onSelect

(Type: function(Date) ) A callback function executed when a date is selected. The selected Date object is passed as an argument.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  onSelect: function(date) {
    console.log('Selected date:', date);
  }
});

onDraw

(Type: function()) A callback function executed after the datepicker is drawn.

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  onDraw: function() {
    console.log('Datepicker drawn');
  }
});

onOpen

(Type: function()) A callback function executed when the datepicker is opened.

onClose

(Type: function()) A callback function executed when the datepicker is closed.

onHide

(Type: function()) A callback function executed when the datepicker is hidden (after closing or being programmatically hidden).

onSetDate

(Type: function(Date)) A callback function executed when the date is set, either by selection or programmatically. The selected Date object is passed as an argument.

Customization

Pikaday allows for extensive customization beyond its configuration options. This section details how to modify its appearance and behavior through styling and event handling.

Themes and Styling

Pikaday’s appearance is primarily controlled by its CSS. The default stylesheet (pikaday.css) provides a basic theme. To create a custom theme, create a new CSS file and override the existing styles. Remember that Pikaday uses a relatively straightforward class structure, making targeting specific elements easy. For example, to change the background color of the calendar container, you might add this to your custom CSS file:

.pika-single {
  background-color: #f0f0f0; /* Change to your desired color */
}

You can inspect the default CSS to identify the classes of the elements you want to style. Consider using a CSS preprocessor like Sass or Less for easier management of complex styles. Remember to include your custom CSS file in your HTML after the default Pikaday CSS to ensure your custom styles override the defaults.

Customizing the Calendar Display

While many aspects of the calendar’s display are controlled by configuration options (like firstDay, format, etc.), some deeper customization might require more involved techniques. For instance, if you need to significantly alter the layout or add completely new elements, you might need to modify the Pikaday JavaScript code itself (though this is generally not recommended unless absolutely necessary, as it will break compatibility with future updates). Consider using the onDraw callback to perform modifications to the calendar’s DOM elements after they are rendered. This allows you to add or manipulate existing elements dynamically. Remember to keep the changes within the confines of the Pikaday structure to prevent unexpected behavior.

For example, you could use onDraw to add a custom class to specific days:

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  onDraw: function() {
    const days = this.el.querySelectorAll('.pika-day');
    days.forEach(day => {
      const date = new Date(day.getAttribute('data-pika-date'));
      if (date.getDate() === 15) { // Example: Add a class to the 15th of every month
        day.classList.add('custom-day');
      }
    });
  }
});

Adding and Removing Events

You can attach custom event listeners to the Pikaday instance or its associated elements. Pikaday provides several built-in events (like onSelect, onOpen, onClose), but you can also add your own. For instance, you could add an event listener to the entire calendar container:

const picker = new Pikaday({
  field: document.getElementById('myDate')
});

picker.el.addEventListener('click', function(event) {
  console.log('Calendar clicked:', event);
});

To remove an event listener, use the appropriate removeEventListener method, providing the same function reference used to add it. Remember that directly manipulating Pikaday’s internal structure is discouraged; use the provided APIs and callbacks whenever possible to maintain compatibility and avoid unintended consequences.

Working with Dates

Pikaday simplifies working with dates, but understanding its date handling is crucial for effective use.

Date Formatting

Pikaday uses Moment.js formatting tokens for date representation. This allows for flexible control over how dates are displayed. The format configuration option determines the output format. Common tokens include:

For example, YYYY-MM-DD produces “2024-10-26”, while DD MMM YYYY produces “26 Oct 2024”. Refer to the Moment.js documentation for a complete list of formatting tokens. The formatStrict option controls how strictly the input date needs to match the specified format.

Date Selection and Manipulation

Pikaday provides several ways to interact with selected dates:

Handling Time Zones

Pikaday primarily deals with dates, not times. While you can set a default time using setDefaultTime, the underlying handling of time zones depends on the browser’s and system’s settings. If time zone considerations are crucial, you should handle the time zone adjustments externally before passing a Date object to Pikaday. The Date object itself inherently contains timezone information.

Working with Different Date Formats

Pikaday’s flexibility stems from its use of Moment.js for date parsing and formatting. To handle different date formats during input, ensure that the format option accurately reflects the expected input format. Pikaday will attempt to parse the input according to the specified format, applying either strict or lenient parsing based on the formatStrict setting. If necessary, you may pre-process the input string to conform to the specified format before it’s presented to Pikaday. For example, if your input is in MM/DD/YYYY format and your format is YYYY-MM-DD, you might need to reformat the input string using JavaScript string manipulation before setting it in the input field.

Accessibility

Pikaday aims to be accessible to users with disabilities. While not perfectly compliant with all accessibility standards out-of-the-box, the following features are included to enhance usability:

Keyboard Navigation

Pikaday supports keyboard navigation for selecting dates. Users can navigate the calendar using the following keys:

This allows users who cannot or prefer not to use a mouse to easily interact with the calendar.

Screen Reader Compatibility

Pikaday utilizes ARIA attributes (see below) to provide information to screen readers. However, complete screen reader compatibility depends on the screen reader’s capabilities and its interpretation of the ARIA attributes. While Pikaday strives for good compatibility, thorough testing with various screen readers is recommended to identify and address any potential issues. Consider adding additional descriptive elements or using techniques for enhanced screen reader accessibility to further improve the experience for users relying on assistive technologies.

ARIA Attributes

Pikaday uses several ARIA attributes to enhance its accessibility:

Proper implementation of these ARIA attributes ensures that screen readers can accurately convey the datepicker’s state and functionality to users. However, remember that relying solely on ARIA attributes might not be sufficient for optimal accessibility; providing clear and concise visual cues is also crucial for users who can see the calendar. Regular testing with assistive technologies is key to ensuring a truly accessible experience.

Troubleshooting

This section covers common problems encountered when using Pikaday, along with debugging techniques and answers to frequently asked questions.

Common Issues and Solutions

Debugging Tips

Frequently Asked Questions (FAQ)

Remember to consult the complete Pikaday documentation and examples for more detailed information and solutions. If you encounter an issue that isn’t covered here, consider searching online forums or reporting the issue directly to the Pikaday project.

Advanced Usage

This section explores more complex scenarios and techniques for utilizing Pikaday effectively.

Integrating with Other Libraries

Pikaday can be integrated with various JavaScript libraries. The key to successful integration lies in understanding how to interact with Pikaday’s API and the APIs of the other libraries. Consider these points:

Successful integration often involves using callbacks like onSelect or onDraw to synchronize data between Pikaday and other libraries.

Creating Custom Plugins

Pikaday doesn’t directly support a plugin architecture. However, you can achieve similar functionality by creating custom functions or extensions that add functionality to your Pikaday instances. This approach typically involves creating functions that interact with the Pikaday API to modify the calendar’s behavior or add custom features. For instance, a custom function could add functionality to highlight specific dates based on external data sources.

Example of a simple custom function to add a class to a specific date:

function highlightDate(picker, date) {
  const day = picker.el.querySelector(`.pika-day[data-pika-date="${date.toDateString()}"]`);
  if(day) day.classList.add('highlighted');
}

const picker = new Pikaday({
  field: document.getElementById('myDate'),
  onSelect: function(date) {
    highlightDate(this, date);
  }
});

This custom function highlightDate adds a class highlighted to the selected date after selection.

Extending Pikaday Functionality

Extending Pikaday’s core functionality beyond simple customizations often requires directly modifying the source code (which is generally discouraged for maintaining compatibility with future updates). However, for very specific needs, you can fork the Pikaday repository and make modifications. Remember that directly modifying the Pikaday source code removes the benefits of automatic updates and may lead to incompatibility problems if you later wish to upgrade the library. If the necessary modification is simple and contained, it might be possible to implement it through well-designed custom functions or callbacks, as described in the “Creating Custom Plugins” section. Choose this option whenever feasible to minimize the risk of conflicts and improve maintainability.

API Reference

This section provides a detailed overview of Pikaday’s API, including its constructor, methods, events, and properties.

Pikaday Constructor

The Pikaday constructor is the primary method for creating a new datepicker instance.

new Pikaday(options)

Parameter:

Return Value:

Methods

The Pikaday object exposes several methods for interacting with the datepicker:

Events

Pikaday triggers several events during its lifecycle. These events can be listened for using the addEventListener method (and removed with removeEventListener). The events are usually triggered on the Pikaday instance’s el element (the calendar container). Refer to the “Customization” section for details on how to listen for and handle Pikaday’s events. Note that some events (like onSelect, onDraw, etc.) are specified as configuration options, where you provide a callback function directly.

Properties

The Pikaday object has several properties:

This is not an exhaustive list; consult the source code for the most up-to-date list of properties. Directly accessing and manipulating internal properties is discouraged unless absolutely necessary. Utilize the provided methods whenever possible to interact with the datepicker.