Spectrum - color picker

spectrum.js

Overview

Spectrum is a jQuery Colorpicker plugin. It is easy to skin and customize the plugin with CSS, and there are a wide range of modes and options to explore. Uses a polyfill for the input[type=color] HTML5 control. This mode needs to work without JavaScript enabled - and fallback to an input[type=text] like other HTML5 inputs. If you don't want this behavior to happen, but still want to use spectrum elsewhere on the page, you can set $.fn.spectrum.load = false; right after loading the script file.

Usage

Include the following lines of code in the <head> section of your HTML:

											
												<!-- Load jQuery -->
												<script type="text/javascript" src="assets/js/jquery/jquery.min.js"></script>

												<!-- Load plugin -->
												<script type="text/javascript" src="assets/js/vendor/pickers/color/spectrum.js"></script>
											
										

Add input element with attributes:

											
												<!-- Markup example -->
												<input type="text" class="form-control colorpicker-basic" value="#20BF7E">
											
										

Call the plugin via JavaScript:

												
													// Basic initialization
													$(".colorpicker-basic").spectrum({
														// options
													});
												
											

Spectrum options and documentation

Full Spectrum documentation can be found online on Official library website. It's very extensive, with lots of options, events and methods.

Plugin info

Property Description
File name spectrum.js
Location assets/js/vendor/pickers/color/
Links

Official plugin website

Full documentation

Github project page

Date range picker

daterangepicker.js

Overview

This date range picker component for Bootstrap creates a dropdown menu from which a user can select a range of dates. Features include limiting the selectable date range, localizable strings and date formats, a single date picker mode, optional time picker (for e.g. making appointments or reservations), and styles that match the default Bootstrap 5 theme

Usage

Include the following lines of code in the <head> section of your HTML:

											
												<!-- Load jQuery -->
												<script type="text/javascript" src="assets/js/jquery/jquery.min.js"></script>

												<!-- Load Moment.js extension -->
												<script type="text/javascript" src="assets/js/vendor/ui/moment/moment.min.js"></script>

												<!-- Load plugin -->
												<script type="text/javascript" src="assets/js/vendor/pickers/daterangepicker.js"></script>
											
										

Add element with attributes:

											
												<!-- Add input field -->
												<input type="text" class="form-control daterange-basic" value="01/01/2015 - 01/31/2015"> 
											
										

Call the plugin via JavaScript:

											
												// Basic initialization
												$('.daterange-basic').daterangepicker({
													parentEl: '.content-inner',
												    applyClass: 'btn-primary',
												    cancelClass: 'btn-light'
												});
											
										

Plugin options

Option Type Description
startDate Date object, moment object or string The start of the initially selected date range
endDate Date object, moment object or string The end of the initially selected date range
minDate Date object, moment object or string The earliest date a user may select
maxDate Date object, moment object or string The latest date a user may select
dateLimit object The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months)
timeZone string or number The timezone that will be used to display the startDate and endDate in the calendar. This may be a string such as "08:00" or an offset in minutes from Greenwich Mean Time. Uses Moment.js #utcOffset. If the timeZone option is not set, the calendar will use the time zone set on the startDate that has been passed in through the options, if it has one. Defaults to the local time zone
showDropdowns boolean Show year and month select boxes above calendars to jump to a specific month and year
showWeekNumbers boolean Show week numbers at the start of each week on the calendars
timePicker boolean Allow selection of dates with times, not just 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 boolean Use 24-hour instead of 12-hour times, removing the AM/PM selection
timePickerSeconds boolean 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
opens string Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to. Available left, right and center
drops string Whether the picker appears below (default) or above the HTML element it's attached to. Available up and down
buttonClasses array CSS class names that will be added to all buttons in the picker
applyClass string CSS class string that will be added to the apply button
cancelClass string CSS class string that will be added to the cancel button
locale object Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars
singleDatePicker boolean 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 boolean Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected
linkedCalendars boolean 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
parentEl string jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body'
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
autoUpdateInput boolean Indicates whether the date range picker should automatically update the value of an <input> element it's attached to at initialization and when the selected dates change

Plugin methods

You can programmatically update the minDate and maxDate in the picker using the setMinDate and setMaxDate methods. You can access the Date Range Picker object and its functions and properties through data properties of the element you attached it to.

Example usage:

											
												// Create a new date range picker
												$('#daterange').daterangepicker({ minDate: '2022-03-05', maxDate: '2022-03-06' });

												// Change the selected date range of that picker
												$('#daterange').data('daterangepicker').setMinDate('2022-03-01');
												$('#daterange').data('daterangepicker').setMaxDate('2022-03-31');
											
										

Available methods

Option Type Description
setStartDate() Date/moment/string Sets the date range picker's currently selected start date to the provided date
setEndDate() Date/moment/string Sets the date range picker's currently selected end date to the provided date

Plugin events

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

Example usage:

											
												// Event example
												$('#daterange').on('cancel.daterangepicker', function(ev, picker) {
													//do something, like clearing an input
													$('#daterange').val('');
												});
											
										

Available events

Event Description
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

Plugin info

Property Description
File name daterangepicker.js
Location assets/js/vendor/pickers/
Links

Official plugin website

Github project page

Date picker

datepicker.min.js

Overview

A vanilla JavaScript remake of bootstrap-datepicker for Bulma and other CSS frameworks. This package is written from scratch as ECMAScript modules/Sass stylesheets to reproduce similar usability to bootstrap-datepicker. It can work either standalone or with CSS framework (e.g. Bootstrap, Foundation), but works best with Bulma as it's developed primarily for Bulma. The package also includes pre-built js/css files for those who like to use it directly on browser.

  • Date picker (input-dropdown, inline), date range picker
  • Keyboard operation support (navigation by arrow keys, editing on input field)
  • i18n support (locales, CSS-based text direction detection)
  • Easily customizable to adapt stylesheet for various CSS frameworks
  • Dependency free
  • Made for modern browsers — no support for IE and Edge Legacy (aka non-Chromium Edge)
    ** If you need to support Edge Legacy, Web Components polyfill will allow this library to run on it.
  • Lightweight (well, relatively…) — 34kB (minified, uncompressed)

Usage

Include the following lines of code in the <head> section of your HTML:

											
												<!-- Load plugin -->
												<script type="text/javascript" src="assets/js/vendor/pickers/datepicker.min.js"></script>
											
										

Add element with attributes:

											
												<!-- Add input field -->
												<input type="text" class="form-control datepicker-basic" placeholder="Pick a date">
											
										

Call the plugin via JavaScript:

											
												// Basic initialization
												const dpBasicElement = document.querySelector('.datepicker-basic');
												if(dpBasicElement) {
													const dpBasic = new Datepicker(dpBasicElement, {
														container: '.content-inner',
														buttonClass: 'btn',
														prevArrow: document.dir == 'rtl' ? '→' : '←',
														nextArrow: document.dir == 'rtl' ? '←' : '→'
													});
												}
											
										

Options

There are 2 kinds of config options: the Datepicker options and the DateRangePicker options. The former are for DatePicker object and the latter are for DateRangePicker object.

Datepicker options can be used with date range picker. And when doing so, you can pass them mixing with DateRangePicker options into one "options" object. Datepicker options passed to date range picker are applied to its start- and end-date pickers.

Aside from a couple of exceptions, config options can be updated dynamically using the setOptions() method.
autohide
Type: Boolean
Default: false
Whether to hide the date picker immediately after a date is selected. Not available in inline picker
beforeShowDay
Type: Function
Default: null

Function to customize the day cells in the days view. The function is called when each day cell is rendered.

  • Arguments:
    • date: {Date} - Date associated with the cell
  • Return:
    • {Object} - Things to customize. Available properties are:
      • enabled: {Boolean} - whether the cell is selectable
      • classes: {String} - space-separated additional CSS classes for the cell element
      • content: {String} - HTML for the cell element's child nodes
    • {String} - additional classes — same as returning { classes: additionalClasses }
    • {Boolean} - whether the cell is selectable — same as returning { enabled: isSelectable }
											
												function (date) {
													let isSelectable, additionalClasses, htmlFragment;
													//...your customization logic

													return {
														enabled: isSelectable,
														classes: additionalClasses,
														content: htmlFragment,
													};
													// Or
													return additionalClasses;
													// Or
													return isSelectable;
												}
											
										
beforeShowDecade
Type: Function
Default: null
Function to customize the decade cells in the decades view. The function is called when each decade cell is rendered. See beforeShowDay for the function details.
beforeShowMonth
Type: Function
Default: null
Function to customize the month cells in the months view. The function is called when each month cell is rendered. See beforeShowDay for the function details.
beforeShowYear
Type: Function
Default: null
Function to customize the year cells in the years view. The function is called when each year cell is rendered. See beforeShowDay for the function details.
buttonClass
Type: String
Default: 'button'
CSS class for <button> elements. (view switch, prev/next buttons, clear and today buttons). This option should be changed to match the button element class of the CSS framework. (e.g. 'btn' for Bootstrap). For constructor only. Cannot be used with setOptions().
calendarWeeks
Type: Boolean
Default: false
Whether to show the week number (ISO week) on week rows.
clearBtn
Type: Boolean
Default: false
Whether to show the clear button.
container
Type: String | HTMLElement
Default: null
The element or CSS selector for the element to append the date picker. By default, date picker is inserted after the associated input field. This option is for changing where to add the date picker. (e.g. to prevent date picker from being clipped when the input field is inside an element styled with overflow: hidden). On inline picker, this option is ignored and overwritten to the associated element. For constructor only, cannot be used with setOptions().
dateDelimiter
Type: String
Default: ','
Delimiter string to separate the dates in a multi-date string. The delimiter must not be included in date format string.
datesDisabled
Type: Array
Default: []
Dates to disable. Array of date strings, Date objects, time values or mix of those. Multi-date string cannot be used. Use multiple single-date strings instead. Given dates are processed to match the pickLevel at the time. If pickLevel is changed dynamically and independently, this option will be reset. This option should be changed together when changing pickLevel dynamically.
daysOfWeekDisabled
Type: Number[]
Default: []
Days of the week to disable. 0:Sunday – 6:Saturday, up to 6 items. Ignored when pickLevel is not 0:date.
daysOfWeekHighlighted
Type: Number[]
Default: []
Days of the week to highlight. 0:Sunday – 6:Saturday, up to 6 items.
defaultViewDate
Type: String|Date|Number
Default: current date
The date to be focused when the date picker opens with no selected date(s).
format
Type: String|Object
Default: 'mm/dd/yyyy'
Date format string. The format string must not include the dateDelimiter string. This option is used to override the one set in the locale specified by language. Alternatively, object that contains custom parser and formatter functions can be used.
											
												{
													format: {
														toValue(date, format, locale) {
															let dateObject;
															//...your custom parse logic
															return dateObject;
														},
														toDisplay(date, format, locale) {
															let dateString;
															//...your custom format logic
															return dateString;
														},
													},
												}
											
										
getCalendarWeek
Type: Function
Default: null
Allows to customize the algorithm how calendar week numbers are calculated. The type of the getCalendarWeek function has to be (date: Date, weekStart: number) => number, where date is the date for which the calendar week number shall be calculated and weekStart is the first day of the week represented by a number between 0 and 6 (0 means Sunday, 1 means Monday, ..., 6 means Saturday). The return value is the calendar week number (1 to 53).
language
Type: String
Default: 'en'
The language code of the language used by the date picker. For languages other than en to work, their locales must be loaded into your project/program.
maxDate
Type: String|Date|Number
Default: null
Maximum limit to selectable date. No limit is applied if null is set. Given date is processed to match the pickLevel at the time. If pickLevel is changed dynamically to higher level independently, this option will be adjusted automatically to the last day of the month or December 31st of the year. This option should be changed together when changing pickLevel to lower level dynamically.
maxNumberOfDates
Type: Number
Default: 1
Maximum number of dates users can select. No limit is applied if 0 is set. Not available for date range picker.
maxView
Type: Number
Default: 3
Maximum limit to the view that the date picker displays. 0:days – 3:decades.
minDate
Type: String|Date|Number
Default: null
Minimum limit to selectable date. No limit is applied if null is set. Given date is processed to match the pickLevel at the time. If pickLevel is changed dynamically to higher level independently, this option will be adjusted automatically to the 1st of the month or January 1st of the year. This option should be changed together when changing pickLevel to lower level dynamically.
nextArrow
Type: String
Default: '»'
HTML (or plain text) for the button label of the "Next" button.
orientation
Type: String
Default: 'auto'
Space-separated string for date picker's horizontal and vertical placement to the associated input field. left|right|auto for horizontal and top|bottom|auto for vertical.
pickLevel
Type: Number
Default: 0
The level that the date picker allows to pick. 0:date, 1: month or 2:year. When this option is 1, the selected date becomes the 1st of the month or, if the date picker is the end-date picker of date range picker, the last day of the month. When this option is 2, the selected date becomes January 1st of the year or, if the date picker is the end-date picker of date range picker, December 31st of the year.
prevArrow
Type: String
Default: '«'
HTML (or plain text) for the button label of the "Prev" button.
showDaysOfWeek
Type: Boolean
Default: true
Whether to show the day names of the week.
showOnClick
Type: Boolean
Default: true
Whether to show the date picker when the associated input filed is clicked.
showOnFocus
Type: Boolean
Default: true
Whether to show the date picker automatically when the associated input filed receives focus.
startView
Type: Number
Default: 0
The view displayed when the date picker opens. 0:days – 3:decades.
title
Type: String
Default: ''
Title string shown in the date picker's title bar. The title bar is not displayed if the title is empty.
todayBtn
Type: Boolean
Default: false
Whether to show the today button.
todayBtnMode
Type: Number
Default: 0
The mode how the today button behaves. If number is 0 - move the focused date to the current date without changing the selection. If number is 1 - select (or toggle the selection of) the current date
todayHighlight
Type: Boolean
Default: false
Whether to highlight the current date.
updateOnBlur
Type: Boolean
Default: true
Whether to update the selected date(s) with the input field's value when the input field is losing focus. When this option is false, if the user edits the date string in input field, it will be parsed and applied only when the user presses the Enter key. If the edit is left unparsed, it will be discarded when input field becomes unfocused (by Tab key press or click outside the picker element/input field).
weekStart
Type: Number
Default: 0
Start day of the week. 0:Sunday – 6:Saturday. This option is used to override the one set in the locale specified by language
allowOneSidedRange
Type: Boolean
Default: false
Whether to allow one side of the date-range to be blank. When this option is false, if the user selects a date on one side while the other side is blank, the date range picker complements the blank side with the same date as the selected side. Similarly, if the user clears one side of the date-range, the date range picker also clears the other side automatically.
inputs
Type: Element[]
Default: input elements inside the associated block element
Input fields to attach start- and end-date pickers. Must contain 2 items. For constructor only, cannot be used with setOptions().

Static properties

Datepicker.locales
Type: Object
Installed locales in [languageCode]: localeObject format. en:English (US) is pre-installed.

Static methods

Datepicker.formatDate()
Type: Function
Format a Date object or a time value using given format and language
											
												Datepicker.formatDate( date , format [, lang ] )
											
										
Datepicker.parseDate()
Type: Function
Parse date string (or Date/time value) using given format and language
											
												Datepicker.parseDate( dateStr , format [, lang ] )
											
										

Instance properties

datepicker.active
Type: Boolean
Whether the picker element is shown (Read-only)
datepicker.pickerElement
Type: HTMLDivElement
DOM object of picker element (Read-only)
datepicker.rangepicker
Type: DateRangePicker
DateRangePicker instance that the datepicker belongs to. Only avalable when the datepicker is a part of date range picker (Read-only)

Instance methods

datepicker.destroy()
Destroy the Datepicker instance
											
												datepicker.destroy()
											
										
datepicker.getDate()
Get selected date(s). The method returns a Date object of selected date by default, and returns an array of selected dates in multidate mode. If format string is passed, it returns date string(s) formatted in given format.
											
												datepicker.getDate( [ format ] )
											
										
datepicker.hide()
Hide the picker element. Not available on inline picker
											
												datepicker.hide()
											
										
datepicker.refresh()
Refresh the picker element and the associated input field
											
												datepicker.refresh( [ target ], [ forceRender ] )
											
										
datepicker.setDate()

Set selected date(s). In multidate mode, you can pass multiple dates as a series of arguments or an array. (Since each date is parsed individually, the type of the dates doesn't have to be the same.). The given dates are used to toggle the select status of each date. The number of selected dates is kept from exceeding the length set to maxNumberOfDates.

With clear: true option, the method can be used to clear the selection and to replace the selection instead of toggling in multidate mode. If the option is passed with no date arguments or an empty dates array, it works as "clear" (clear the selection then set nothing), and if the option is passed with new dates to select, it works as "replace" (clear the selection then set the given dates).

When render: false option is used, the method omits re-rendering the picker element. In this case, you need to call refresh() method later in order for the picker element to reflect the changes. The input field is refreshed always regardless of this option.

When invalid (unparsable, repeated, disabled or out-of-range) dates are passed, the method ignores them and applies only valid ones. In the case that all the given dates are invalid, which is distinguished from passing no dates, the method considers it as an error and leaves the selection untouched. (The input field also remains untouched unless revert: true option is used.)
											
												datepicker.setDate( date1 [, date2 [, ... dateN ]][, options ] )
												datepicker.setDate( dates [, options ] )
												datepicker.setDate( [ options ] )
											
										
datepicker.setOptions()
Set new values to the config options
											
												datepicker.setOptions( options )
											
										
datepicker.show()
Show the picker element
											
												datepicker.show()
											
										
datepicker.update()
Update the selected date(s) with input field's value. Not available on inline picker. The input field will be refreshed with properly formatted date string. In the case that all the entered dates are invalid (unparsable, repeated, disabled or out-of-range), whixh is distinguished from empty input field, the method leaves the input field untouched as well as the selection by default. If revert: true option is used in this case, the input field is refreshed with the existing selection.
											
												datepicker.update( [ options ] )
											
										

Events

All Datepicker-event objects are CustomEvent instances and dispatched to the associated <input> element (for inline picker, the block element). They include the following extra data in the detail property.
  • date: {Date} - Selected date(s)
  • viewDate: {Date} - Focused date
  • viewId: {Number} - ID of the current view
  • datepicker: {Datepicker} - Datepicker instance
changeDate
Fired when the selected dates are changed
changeMonth
Fired when the focused date is changed to a different month's date.
changeView
Fired when the current view is changed.
changeYear
Fired when the focused date is changed to a different year's date.
hide
Fired when the date picker becomes hidden.
show
Fired when the date picker becomes visible.

Date format

Date format must be declared using the combination of the predefined tokens and separators.
Token Description Example
d day of the month without leading zero 1, 2, ..., 31
dd day of the month with leading zero 01, 02, ..., 31
D shortened day name of the week Sum, Mon, ..., Sat
DD full day name of the week Sunday, Monday, ..., Saturday
m numeric month without leading zero 1, 2, ..., 12
mm numeric month with leading zero 01, 02, ..., 12
M shortened month name Jan, Feb, ..., Dec
MM full month name January, February, ..., December
y year without leading zero 1, 645, 1900, 2020
yy 2-digit year with leading zero 01, 45, 00, 20
yyyy 4-digit year with leading zero 0001, 0645, 1900, 2020

Date string

Date strings are expected to be formatted in the date format set in the format config option (default: mm/dd/yyyy), but it isn't necessary to match the format strictly.
How Built-in Parser parses

The built-in parser uses the format string only to determine the sequence in which the date parts (year/month/day/day-of-the-week) and separators appear in the date string. The differences in separator characters, whether to have leading zeros and whether month name (full or short) or month number is used are ignored. Therefore, as long as the parts of a date string appear in the same order as the format's, the variations of the same date's date string are equally parsed to the same date.

There are some cases the parser treats the parts in specific way:

  • year is treated as full year (1-/2-digit years are not mapped to nearby century's)
  • month number not between 1 and 12 is treated in the similar way to Date.prototype.setMonth()
  • month name is evaluated in case-insensitive begin-with match
  • day not between 1 and last-day-of-the-month is treated in the same way as Date.prototype.setDate()
  • day-of-the-week is not evaluated (not totally ignored, the existence is respected)
  • if a part is omitted from the format, missing in the date string or parsed unsuccessfully, current date's value is used to complement.

Here are some examples of how irregular date strings are parsed.

  • Different separators from the format:
    • if format is yyyy-mm-dd, 2020/04/22April 22nd, 2020
    • if format is m.d.y, 1/15 (2018)January 15th, 2018
  • With/without leading zeros:
    • if format is d/m/y, 05/06/07June 5th, 0007
    • if format is yyyy-mm-dd, 20-5-4May 4th, 0020
  • Number for the month name:
    • if format is M-d-y, 7-14-2020July 14th, 2020
  • Incomplete month name/full name for short name:
    • if format is M-d-y,
      • ap-22-2020April 22nd, 2020
      • sept-22-2020September 22nd, 2020
      • Ju-4-2020June 4th, 2020
      • July-4-2020July 4th, 2020
  • Month/day outside the normal range:
    • if format is mm/dd/yyyy,
      • 14/31/2019March 2nd, 2020
      • 0/0/2020November 30th, 2019
  • Omitted/missing/invalid parts:
    • if format is mm/yyyy and current date is January 15th, 2020,
      • 04/2022April 15th, 2022
    • if format is m/d/y and current date is January 15th, 2020,
      • 4/22April 22nd, 2020
      • /22/2016January 22nd, 2016
      • 7/xx/2016July 15th, 2016
  • Day-of-the-week:
    • if format is D m/d y and current date is January 15th, 2020,
      • xx 5/4 2022May 4th, 2022
      • 5/4 2022October 13th, 2025 (= April 2022nd, 2020)
'Today' shortcut
You can use 'today' as a shortcut to the current date.
Multiple dates
You can combine multiple dates into a single date string by joining the dates with the delimiter set in the dateDelimiter config option.

Plugin info

Property Description
File name datepicker.min.js
Location assets/js/vendor/pickers/
Links

Official plugin website

Github project page