pickadate.js - Documentation

Getting Started

Installation

Pickadate.js can be integrated into your project in several ways:

1. Download: Download the latest release from the GitHub releases page and include the picker.js and picker.date.js (for date picker) or picker.time.js (for time picker) files in your project. You’ll also likely want the CSS file, themes/default.css or a custom theme.

2. Bower: If you use Bower, install it via:

bower install pickadate

3. npm: If you use npm, install it via:

npm install pickadate

4. CDN: Use a CDN like jsDelivr:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pickadate/lib/themes/default.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pickadate/lib/themes/default.date.css">
<script src="https://cdn.jsdelivr.net/npm/pickadate/lib/picker.js"></script>
<script src="https://cdn.jsdelivr.net/npm/pickadate/lib/picker.date.js"></script>
```  Remember to replace `default.css` and `default.date.css` with the desired theme files if needed.


After installation, include the necessary JavaScript and CSS files in your HTML `<head>` section.  Make sure the order is correct (CSS first, then JavaScript).


### Basic Usage

Pickadate.js uses a simple jQuery-like syntax.  After including the necessary files,  you initialize the datepicker on an input field by calling the `datepicker` method on your input element. This method accepts an options object (see below for details).


```javascript
$(document).ready(function(){
  $('#datepicker').pickadate();
});

Replace #datepicker with the ID of your input element. This will create a basic datepicker.

First Example

This example shows a simple datepicker implementation:

<!DOCTYPE html>
<html>
<head>
<title>Pickadate.js Example</title>
<link rel="stylesheet" href="themes/default.css">
<link rel="stylesheet" href="themes/default.date.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>  <!-- Or your jQuery source -->
<script src="picker.js"></script>
<script src="picker.date.js"></script>
</head>
<body>

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

<script>
  $(document).ready(function(){
    $('#datepicker').pickadate();
  });
</script>

</body>
</html>

Remember to replace "themes/default.css", "themes/default.date.css", "picker.js", and "picker.date.js" with the actual paths to your files. This code creates a basic date picker attached to the input field with the id “datepicker”. You can then expand upon this by adding options to customize the appearance and behavior.

Core Concepts

Date Object

Pickadate.js internally uses a date object representation that extends beyond the native JavaScript Date object. This allows for more robust handling of dates, including setting and retrieving specific date components (year, month, day) and handling of date ranges and formats. While you generally don’t interact directly with this internal representation, understanding its capabilities is helpful for interpreting options and events. The internal object contains properties like year, month, date, day, hours, minutes, seconds, etc., reflecting the selected date and time. Methods are available to manipulate these properties, often through configuration options.

Time Object

Similar to the date object, Pickadate.js uses an internal time object (primarily for time pickers). This object provides a structured way to represent and manipulate time components like hours, minutes, seconds, and potentially AM/PM indicators. You’ll rarely interact with this directly; it’s primarily used under the hood to manage the time picker’s functionality. Configuration options influence how the time is presented and what time units are included (e.g., hours, minutes, seconds).

Selectors

Pickadate.js uses standard jQuery selectors to target the input element where the picker should be attached. You specify the input field using a jQuery selector like #myDateInput (for an element with the ID “myDateInput”) or .myDateClass (for elements with the class “myDateClass”). This selector is passed to the pickadate function to initialize the picker on the selected element(s). Make sure that the selector correctly identifies the target element(s) in your HTML.

Options

Pickadate.js offers a comprehensive set of options to customize the date and time pickers’ appearance and behavior. These options are passed as a JavaScript object to the pickadate function. Common options include:

Consult the detailed options list in the Pickadate.js documentation for a complete reference.

Events

Pickadate.js triggers several events throughout its operation. These events allow you to respond to user interactions and picker state changes. You can bind event handlers to these events using jQuery’s .on() method. Important events include:

You can use these events to perform actions such as updating other elements on the page, validating the selected date, or handling custom user input. See the documentation for a full list of events and their parameters.

Configuration Options

Setting the Date

You can set the initial date displayed in the picker using the select option. This option accepts a JavaScript Date object or a string that conforms to your specified format option.

$('#datepicker').pickadate({
  select: new Date(), // Sets the current date
  select: '2024-03-15', // Sets a specific date (format must match the 'format' option)
});

If select is omitted, the picker will initially display the current date.

Date Ranges

Restrict the selectable dates using the min and max options. These options accept a Date object or a string representing the minimum and maximum allowable dates, respectively.

$('#datepicker').pickadate({
  min: new Date(2023, 0, 1), // Minimum date: January 1st, 2023
  max: new Date(2024, 11, 31) // Maximum date: December 31st, 2024
});

Selecting Specific Dates

You can pre-select specific dates that will be highlighted in the picker calendar using the onSet option.

$('#datepicker').pickadate({
    onSet: function(e){
        if (e.select) {
            this.setDate('2024-04-10', true, true); //Selects April 10th 2024
        }
    }
});

This allows for certain dates to be visually emphasized or set in advance.

Disabling Dates

Disable specific dates using the disable option. This option accepts an array of Date objects or strings representing dates to disable.

$('#datepicker').pickadate({
  disable: [
    new Date(2024, 2, 15), // Disable March 15th, 2024
    new Date(2024, 2, 20) // Disable March 20th, 2024
  ]
});

You can also use functions for more dynamic disabling:

$('#datepicker').pickadate({
  disable: function(date) {
    //Disable weekends
    return date.getDay() === 0 || date.getDay() === 6;
  }
});

Formatting Options

Customize the date and time display formats using the format, formatSubmit, monthsFull, monthsShort, weekdaysFull, weekdaysShort, and weekdaysLetter options. Refer to the documentation for the supported format codes.

$('#datepicker').pickadate({
  format: 'yyyy-mm-dd',
  formatSubmit: 'yyyy/mm/dd',
  monthsFull: ['Enero', 'Febrero', 'Marzo', ...], // Custom month names
});

Localization

Pickadate.js offers built-in support for various locales. You can specify the locale using the i18n option. For example to use Spanish:

$('#datepicker').pickadate({
    i18n: {
        monthsFull: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthsShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        weekdaysFull: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
        weekdaysShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'],
        today: 'Hoy',
        clear: 'Limpiar',
        close: 'Cerrar',
        firstDay: 1 // Monday
    }
});

View Options

Control the initial view of the picker using the selectMonths and selectYears options. Setting these to true allows users to select months and years, while false disables these selection steps. The view option will let you control which view shows on startup (e.g., years, months).

$('#datepicker').pickadate({
  selectMonths: true,
  selectYears: true
});

Input Field Customization

You can style the input field using CSS, but Pickadate.js also provides options to customize its behavior. For example, container allows you to specify a custom container element for the picker to reside within (instead of being placed directly next to the input field).

Theme Customization

Pickadate.js uses CSS for theming. You can create your custom theme by creating a new CSS file and modifying the existing styles or starting from scratch. You then reference your new CSS file in your HTML.

Accessibility Options

While Pickadate.js doesn’t have explicit accessibility options, best practices for ARIA attributes and semantic HTML should be applied to ensure proper accessibility. Ensure that your input field has appropriate ARIA attributes, and consider using keyboard navigation for testing and accessibility. For optimal accessibility, additional testing with assistive technologies is recommended.

Working with Dates

Setting and Getting Dates

Pickadate.js provides methods to easily set and retrieve the selected date. The primary method for setting a date is through the select option during initialization, as described in the Configuration Options section. To get the currently selected date, use the get method of the picker object:

var picker = $('#datepicker').pickadate();
var selectedDate = picker.get(); // Returns an object representing the selected date

console.log(selectedDate.select); // Access the selected date
console.log(selectedDate.formatted); // Access formatted date string (based on format option)

//Set a new date
picker.set('2025-01-15');

The get() method returns a date object with various properties such as select, formatted, object, etc. Refer to the documentation for detailed information about these properties.

Date Manipulation

While Pickadate.js doesn’t directly expose methods for complex date arithmetic (like adding/subtracting months or years directly on the picker object), you can achieve date manipulation using native JavaScript’s Date object. Get the date using picker.get().select (which gives you a native Date object), manipulate it, and then set it back using picker.set().

var picker = $('#datepicker').pickadate();
var currentDate = picker.get().select;

// Add 7 days
currentDate.setDate(currentDate.getDate() + 7);
picker.set(currentDate);

Date Calculations

For more complex date calculations (finding the difference between two dates, determining weekdays, etc.), you’ll need to use JavaScript’s Date object methods or external libraries like Moment.js. Pickadate.js itself focuses on date selection and formatting; it doesn’t include extensive date calculation capabilities built-in.

Parsing Dates

Pickadate.js handles date parsing based on the format option specified during initialization. If you need to parse dates from strings that don’t conform to your configured format, you must manually parse them using JavaScript’s Date.parse() or a date parsing library. However, it’s generally best to ensure consistent date string formats throughout your application to avoid parsing issues.

Formatting Dates

Pickadate.js automatically formats the selected date according to the format option provided during initialization. The selected date is also available in a formatted string via picker.get().formatted. If you need additional date formatting beyond the default options, use JavaScript’s toLocaleDateString() or a dedicated date formatting library like Moment.js for more control. You can also specify formatSubmit to control the date format for form submissions.

Advanced Usage

Customizing the Picker UI

Beyond the options for customizing text and formats, you can significantly alter the Pickadate.js picker’s visual appearance through CSS. Target the classes applied to the picker’s various elements (check the generated HTML source to identify these classes) and style them according to your needs. You can create a completely custom theme by creating a new CSS file and overriding the default styles. Remember to avoid overly complex or specific CSS selectors that might break when the library is updated.

Integrating with other libraries

Pickadate.js is designed to work well with other JavaScript libraries. It relies on jQuery for DOM manipulation, so ensure jQuery is included before including Pickadate.js. For date manipulation and more advanced date calculations, consider integrating libraries like Moment.js. You can seamlessly incorporate Pickadate.js into larger frameworks like React, Angular, or Vue.js by incorporating it into your component structure and managing its lifecycle using the framework’s methods.

Handling Events

Pickadate.js provides a set of events that allow you to react to various actions within the picker, such as date selection (set), picker opening (open), and picker closing (close). Use jQuery’s .on() method to bind event handlers to these events. The event handlers will receive an event object containing information about the event. This allows for dynamic updates to your application based on user interactions with the date picker. For example, you could update other form fields based on the selected date or perform validation.

$('#datepicker').pickadate({
  onSet: function(e) {
    if (e.select) {
      console.log('Date selected:', e.select);
      // Perform actions based on selected date
    }
  },
  onClose: function() {
    console.log('Picker closed');
    // Perform actions when picker closes
  }
});

Accessibility Considerations

While Pickadate.js itself doesn’t include specific accessibility features, it’s crucial to incorporate them within your implementation. This includes adding appropriate ARIA attributes to the input field and the picker elements to provide sufficient information to assistive technologies. Ensure that the picker is usable with keyboard navigation alone. Test your implementation with screen readers and other assistive technologies to verify accessibility. Consider using descriptive labels for buttons and ensuring sufficient color contrast for visual clarity.

Performance Optimization

For optimal performance, especially when dealing with a large number of date pickers on a single page, consider these points:

Troubleshooting

Common Issues

Debugging Tips

Error Messages

Pickadate.js generally doesn’t throw many explicit error messages. Instead, problems often manifest as the picker failing to appear or not behaving as expected. JavaScript errors in your browser’s developer console are the most likely source of information about problems. Pay close attention to the error messages, line numbers, and file names to diagnose the issue.

Browser Compatibility

Pickadate.js generally supports modern browsers. However, older browsers might exhibit quirks or require polyfills for certain features. Always test your application across your target browsers to ensure compatibility. The documentation should list the officially supported browser versions. If you encounter issues in older browsers, you might need to use a polyfill to provide missing functionality or consider using a more widely compatible date picker library.

API Reference

This section provides a reference to the core methods, properties, and events exposed by the Pickadate.js library. Note that the exact API might vary slightly depending on the version of Pickadate.js you’re using. Always consult the latest official documentation for the most up-to-date information.

Methods

Pickadate.js’s primary method for interacting with a date/time picker is to obtain a picker object using jQuery’s pickadate() method on your target input element. The returned object then exposes several methods:

These are some of the core methods. Consult the official Pickadate.js documentation for a complete list and detailed descriptions of each method’s parameters and return values.

Properties

The picker object itself doesn’t directly expose many public properties. The most important information, such as the selected date and its formatted representation, is accessed through the picker.get() method’s return object. Directly accessing internal properties of the picker object is generally discouraged, as these internals may change in future versions of the library.

Events

Pickadate.js provides several events that you can listen for using jQuery’s .on() method. These allow you to react to user actions and changes in the picker’s state. The most commonly used events are:

You would typically bind these events using the following syntax (replace 'set' with the event name):

$('#datepicker').pickadate().on('set', function(e) {
  // Handle the 'set' event
  console.log(e);
});

Again, consult the official documentation for a complete list of events and details on the data passed to their event handlers. Remember that the events are jQuery events, so you can use standard jQuery event handling methods to manage them.