DatePicker

A Panel which can display a month of date cells, which navigates between the cells, fires events upon user selection actions, optionally navigates to other months in response to UI gestures, and optionally displays information about each date cell. Appearance in the built-in themes:

Date picker
//<code-header>
fiddle.title = 'Date picker';
//</code-header>
const picker = new DatePicker({
    appendTo          : targetElement,
    width             : '24em',
    date              : DateHelper.add(new Date(), '1d'),
    onSelectionChange : ({ selection }) => {
        Toast.show(`You picked ${DateHelper.format(selection[0], 'MMM DD')}`);
    }
});

A date is selected (meaning a single value is selected if multiSelect is not set, or added to the selection if if set) by clicking a cell or by pressing ENTER when focused on a cell.

The SHIFT and CTRL keys modify selection behaviour depending on the value of multiSelect.

This class is used as a picker by the DateField class.

Styling cell content via CSS

Several different CSS classes are applied to date cells depending on their state. These can be used to style contents of cells via CSS.

  • b-disabled-date - Applied to disabled days
  • b-weekend - Applied to weekend days
  • b-past-date - Applied to dates before today
  • b-today - Applied to today's date
  • b-non-working-day - Applied to dates which are nonWorkingDays

By default, disabled dates in a lighter color. You can override this in your own CSS, using the CSS variable API of this class.

Custom cell rendering

You can easily control the content of each date cell using the cellRenderer. The example below shows a view typically seen when booking hotel rooms or apartments.

Date picker cell renderer
//<code-header>
fiddle.title = 'Date picker cell renderer';
CSSHelper.insertRule('#datePickerCellRenderer .b-calendar-panel-cell .b-date-picker-cell-inner { padding:0.5em 1.2em 1.2em 1.2em;}', targetElement.getRootNode());
CSSHelper.insertRule('#datePickerCellRenderer .b-date-picker-cell-payload { bottom:0.75em;}', targetElement.getRootNode());
CSSHelper.insertRule('.price { font-size: 0.65em;}', targetElement.getRootNode());
CSSHelper.insertRule('.b-calendar-panel-cell:not(.b-active-date) .price { opacity:0.65; }', targetElement.getRootNode());
//</code-header>
const prices = [
        110, 80, 0, 70, 120, 80, 90,
        90, 110, 80, 0, 0, 120, 80, 90,
        90, 130, 60, 0, 70, 80, 90
    ],
    picker = new DatePicker({
        id       : 'datePickerCellRenderer',
        appendTo : targetElement,
        width    : '27em',
        date     : new Date(),

        cellRenderer({ cell, cellPayload, date }) {
            const
                sameMonth = date.getMonth() === this.date.getMonth(),
                price     = prices[date.getDate()];

            cellPayload.classList.add('price');
            cellPayload.innerHTML = `${sameMonth && price ? ('$' + price) : '&nbsp;'}`;

            delete cell.dataset.btip;
            if (sameMonth) {
                cell.dataset.btip = price ? `Flights available from: <strong>$${price}</strong>` : 'No flights available';
            }
        },

        onSelectionChange : ({ selection }) => {
            Toast.show(`You picked ${DateHelper.format(selection[0], 'MMM DD')}`);
        }
    });

Multi selection

You can select multiple date ranges or a single date range using the multiSelect config.

Multi-select date picker
//<code-header>
fiddle.title = 'Multi-select date picker';
//</code-header>
const startDate = new Date(new Date().setDate(15));
while (startDate.getDay() !== 3) {
    startDate.setDate(startDate.getDate() - 1);
}
const endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + 7);

const picker = new DatePicker({
    appendTo  : targetElement,
    width     : '24em',
    selection : [
        startDate,
        endDate
    ],
    multiSelect : 'range',
    bbar        : {
        items : {
            toggleMultiSelect : {
                type        : 'buttongroup',
                toggleGroup : true,
                rendition   : 'padded',
                style       : 'margin : 0 auto',
                items       : {
                    multi : {
                        text : 'Multi range'
                    },
                    single : {
                        text    : 'Single range',
                        pressed : true
                    }
                },
                onToggle({ source, pressed }) {
                    if (pressed) {
                        picker.multiSelect = source.ref === 'multi' ? true : 'range';

                        // Cut down range if we switch to a single range
                        if (picker.multiSelect === 'range') {
                            picker.selection.length && (picker.selection = picker.activeDate);
                        }
                    }
                }
            }
        }
    },
    onSelectionChange : ({ source, selection }) => {
        if (source.multiSelect === 'range') {
            Toast.show(`Date range ${DateHelper.format(selection[0], 'MMM DD')} to ${DateHelper.format(selection[1], 'MMM DD')}`);
        }
        else {
            Toast.show(`${selection.length} dates selected`);
        }
    }
});

Configuring toolbar buttons

The datepicker includes a few useful navigation buttons by default. Through the DatePicker´s toolbar, you can manipulate these, via the toolbar´s items config.

There are four buttons by default, each of which can be reconfigured using an object, or disabled by configuring them as null.

new DatePicker({
   tbar : {
      // Remove all navigation buttons
      items : {
          prevYear  : null,
          prevMonth : null,
          nextYear  : null,
          nextMonth : null
      }
   },
   bbar : {
       items : {
           todayButton : {
               text     : 'Today',
               style    : 'margin-inline:auto',
               onClick  : 'up.onTodayClick'
           }
       }
   },
   onTodayClick() {
       this.date = new Date();
   }
})

Date picker buttons
//<code-header>
fiddle.title = 'Date picker buttons';
//</code-header>
const picker = new DatePicker({
    appendTo : targetElement,
    width    : '24em',
    date     : new Date(2025, 5, 1),
    tbar     : {
        // Remove all navigation buttons
        items : {
            // Hide previous/next year buttons
            prevYear : null,
            nextYear : null

            // Uncommend to hide previous/next month buttons
            // prevMonth : null,
            // nextMonth : null
        }
    },
    bbar : {
        items : {
            todayButton : {
                text      : 'Today',
                style     : 'margin-inline:auto',
                onClick   : 'up.onTodayClick',
                rendition : 'filled'
            }
        }
    },
    onTodayClick() {
        this.date = new Date();
    }
});

Provided toolbar widgets include:

  • prevMonth Navigates to previous month
  • nextMonth Navigates to next month
  • prevYear Navigates to previous year
  • nextYear Navigates to next year

Configs

145

Common

listenersEvents

Other

activeDate: Date | today | String

The date that the user has navigated to using the UI prior to setting the widget's value by selecting it. The initial default is today's date. Can also be supplied as a YYYY-MM-DD date string.

This may be changed using keyboard navigation. The date is set by pressing ENTER when the desired date is reached.

Programmatically setting the date, or using the UI to select the date by clicking it also sets the activeDate

cellRenderer: function | String

A function (or the name of a function) which creates content in, and may mutate a day cell element.

The intention of this function is to allow you to augment the existing cell with additional information about the date.

The cell structure passed in the cell property is as follows:

<div class="b-calendar-panel-cell" data-date="2024-09-15">
    <div class="b-date-picker-cell-inner" role="presentation">15</div>
    <div class="b-date-picker-cell-payload"></div>
</div>

The b-calendar-panel-cell element is the cell element itself. It contains two child elements:

  • b-date-picker-cell-inner: This element contains the date number.
  • b-date-picker-cell-payload: This element is empty by default and can be used to augment the cell content.

The payload element is absolutely positioned, docked to the bottom of the cell. You may add content to this element, and target it with CSS to augment the cell content.

If you return content, textual HTML will replace the contents of the cell element. A DomConfig object will be used by sync to update the cell element. If you want to augment the cell, it is recommended to add content to the cellPayload element.

ParameterTypeDescription
renderDataObject
renderData.cellHTMLElement

The cell's encapsulating element. This has the b-calendar-panel-cell class and is the element which receives focus, so this should be the target of any accessibility attributes.

renderData.innerCellHTMLElement

The inner element of the cell which contains the date number. This is the aspect-ratio : 1 element which contains the date. It is not recommeneded to mutate this element. Instead use the cellPayload element (see below).

renderData.cellPayloadHTMLElement

An empty, absolutely positioned element, by default docked at the bottom of the cell. Content may be added to this element to augment cell content.

renderData.dateDate

The date for the cell

renderData.dayNumber

The day for the cell (0 to 6 for Sunday to Saturday)

renderData.rowIndexNumber[]

The row index, 0 to month row count (6 if sixWeeks is true)

renderData.rowHTMLElement

The row element encapsulating the week which the cell is a part of

renderData.sourceCalendarPanel

The widget being rendered

renderData.cellIndexNumber[]

The cell index in the whole panel. May be from 0 to up to 42

renderData.columnIndexNumber[]

The column index, 0 to 6

renderData.visibleColumnIndexNumber[]

The visible column index taking hidden non working days into account

Returns: String | DomConfig | null
date: Date | String

The initially selected date (or a YYYY-MM-DD date string).

dayNameFormat: String= dd

The DateHelper format string to format the day names.

This property is only valid if multiSelect is set to 'range' or true.

Configure as true to enable selecting a date range by dragging the mouse pointer across date cells while holding the primary mouse button down.

If multiSelect is set to true, use CTRL (CMD on Mac) while dragging to select multiple ranges.

editMonth: Boolean= true

By default, the month and year are editable. Configure this as false to prevent that.

By default, disabled dates cannot be navigated to, and they are skipped over during keyboard navigation. Configure this as true to enable navigation to disabled dates.

Configure as true to add a highlighted border and background to the week row which encapsulates the selected date.

includeYear: Boolean= true

By default, the year is visible. Configure this as false to prevent that.

maxDate: Date

The maximum selectable date. Selection of and navigation to dates after this date will not be possible.

minDate: Date

The minimum selectable date. Selection of and navigation to dates prior to this date will not be possible.

monthButtonFormat: String= 'MMMM'

The format string to use to create the text of the month button.

It defaults to showing the full localized month name.

multiSelect: Boolean | range | simple= false

Configure as true to enable selecting multiple discontiguous date ranges using click and Shift+click to create ranges and Ctrl+click to select/deselect individual dates.

Configure as 'simple' to enable selecting a single date range by clicking a start date followed by the end date. If you configure multiSelect range on touch-devices, simple will be the mode used.

Configure as 'range' to enable selecting a single date range by selecting a start and end date. Hold "SHIFT" button to select date range. Ctrl+click may add or remove dates to/from either end of the range.

If 'range' is used, then the dragSelect config may be used to enable range selection by dragging the mouse pointer across date cells while holding the primary mouse button down.

selection: Date[] | String[]Also a property

If multiSelect is configured as true, this is an array of dates which are selected. There may be multiple, discontiguous date ranges.

If multiSelect is configured as 'range' or 'simple', this is a two element array specifying the first and last selected dates in a range.

You can also provide the selected dates as an array of YYYY-MM-DD date strings

animateTimeShiftCalendarPanel
columnWidget
defaultFocusContainer
disabledClsCalendarPanel
disabledDatesCalendarPanel
disableWeekendsCalendarPanel
drawerPanel
headerRendererCalendarPanel
hideOtherMonthCellsCalendarPanel
labelPositionContainer
minColumnWidthCalendarPanel
minRowHeightCalendarPanel
monthCalendarPanel
nonWorkingDayClsCalendarPanel
nonWorkingDaysCalendarPanel
otherMonthClsCalendarPanel
renditionContainer
rtlRTL
shadePastDatesCalendarPanel
showWeekColumnCalendarPanel
sixWeeksCalendarPanel
spanWidget
tipCalendarPanel
todayClsCalendarPanel
weekColumnHeaderCalendarPanel
weekendClsCalendarPanel
weekRendererCalendarPanel
weekStartDayCalendarPanel

Accessibility

ariaLabelWidget
keyMapKeyMap

Content

bbarPanel
defaultsContainer
footerPanel
headerPanel
itemsContainer
lazyItemsContainer
namedItemsContainer
stripsPanel
tbarPanel
textContentContainer
toolsPanel

CSS

bodyClsPanel
borderContainer
clsWidget
colorWidget
htmlClsWidget
itemClsContainer
styleWidget
uiPanel

DOM

adoptWidget
appendToWidget
contentWidget
datasetWidget
htmlWidget
idWidget
tagWidget

Float & align

alignWidget
anchorWidget
centeredWidget
draggableWidget
floatingWidget
xWidget
yWidget

Layout

alignSelfWidget
dockWidget
flexWidget
heightWidget
hiddenWidget
hideWhenEmptyContainer
layoutContainer
layoutStyleContainer
marginWidget
maxHeightWidget
maxWidthWidget
minHeightWidget
minWidthWidget
textAlignWidget
weightWidget
widthWidget

misc

tabBarItemsContainer

Misc

dataFieldWidget
disabledWidget
iconPanel
localeClassLocalizable
localizableLocalizable
maskedWidget
ownerWidget
readOnlyWidget
refWidget
rippleWidget
tabWidget
titlePanel
tooltipWidget

Record

recordContainer

Scrolling

State

stateIdState

Properties

106

Class hierarchy

isDatePicker: Boolean= truereadonly
Identifies an object as an instance of DatePicker class, or subclass thereof.
isDatePicker: Boolean= truereadonlystatic
Identifies an object as an instance of DatePicker class, or subclass thereof.
isCalendarPanelCalendarPanel
isContainerContainer
isDelayableDelayable
isEventsEvents
isKeyMapKeyMap
isLocalizableLocalizable
isPanelPanel
isStateState
isToolableToolable
isWidgetWidget

Other

dragSelect: Boolean= falseAlso a config

This property is only valid if multiSelect is set to 'range' or true.

Configure as true to enable selecting a date range by dragging the mouse pointer across date cells while holding the primary mouse button down.

If multiSelect is set to true, use CTRL (CMD on Mac) while dragging to select multiple ranges.

Configure as true to add a highlighted border and background to the week row which encapsulates the selected date.

The selected Date(s).

When multiSelect is 'range', then this yields a two element array representing the start and end of the selected range.

When multiSelect is true, this yields an array containing every selected Date.

$namestaticWidget
animateTimeShiftCalendarPanel
columnWidget
dateCalendarPanel
endDateCalendarPanel
firstItemContainer
hasChangesContainer
isValidContainer
itemsContainer
labelPositionContainer
lastItemContainer
renditionContainer
rtlRTL
shadePastDatesCalendarPanel
showWeekColumnCalendarPanel
spanWidget
startDateCalendarPanel
toolsPanel
typestaticWidget
valuesContainer
visibleWeekCountCalendarPanel
weekColumnHeaderCalendarPanel

Accessibility

keyMapKeyMap

Content

bbarPanel
tbarPanel

CSS

clsWidget

DOM

appendToWidget
contentWidget
datasetWidget
elementWidget
htmlWidget
idWidget
styleWidget

Float & align

xWidget
yWidget

Layout

alignSelfWidget
flexWidget
heightWidget
layoutContainer
layoutStyleContainer
marginWidget
maxHeightWidget
maxWidthWidget
minHeightWidget
minWidthWidget
widthWidget

Lifecycle

configBase

Misc

cellInfoWidget
disabledWidget
localeHelperLocalizable
localeManagerLocalizable
readOnlyWidget
refWidget
tabWidget
titlePanel
tooltipWidget

Record

recordContainer

State

stateState

Visibility

hiddenWidget
isVisibleWidget

Widget hierarchy

ownerWidget
parentWidget
widgetMapContainer

Functions

79

Other

Checks whether a date is selected.

ParameterTypeDescription
dateDate

The date

Returns: Boolean
addContainer
composeWidget
createOnFrameDelayable
disableWidget
enableWidget
focusWidget
getAtContainer
getCellCalendarPanel
getWidgetByIdContainer
insertContainer
LstaticLocalizable
maskWidget
onEvents
recomposeWidget
refreshCalendarPanel
relayAllEvents
removeContainer
removeAllContainer
resetValuesContainer
setValuesContainer
triggerEvents
unEvents
unmaskWidget
updateDateCalendarPanel
updateWeekStartDayCalendarPanel

Configuration

applyDefaultsstaticBase

Events

Float & align

alignToWidget
setXYWidget
showByWidget
toFrontWidget

Lifecycle

createstaticWidget
destroystaticBase
initClassstaticWidget

Misc

attachTooltipstaticWidget
fromElementstaticWidget
fromSelectorstaticWidget
getByIdstaticWidget
isOfTypeNamestaticBase
mixinstaticBase
optionalLstaticLocalizable

State

Visibility

hideWidget
showWidget

Widget hierarchy

closestWidget
containsWidget
ownsWidget
queryWidget
queryAllWidget
upWidget

Events

27

Fires when a date or date range is selected. If multiSelect is specified, this will fire upon deselection and selection of dates.

// Adding a listener using the "on" method
datePicker.on('selectionChange', ({ selection, oldSelection, userAction }) => {

});
ParameterTypeDescription
selectionDate[]

The selected dates. If multiSelect is specified this may be a two element array specifying start and end dates.

oldSelectionDate[]

The previously selected dates. If multiSelect is specified this may be a two element array specifying start and end dates.

userActionBoolean

This will be true if the change was caused by user interaction as opposed to programmatic setting.

beforeRefreshCalendarPanel
catchAllEvents
cellClickCalendarPanel
dateChangeCalendarPanel
destroyEvents
expandPanel
focusInWidget
focusOutWidget
hideWidget
paintWidget
readOnlyWidget
recomposeWidget
refreshCalendarPanel
resizeWidget
showWidget
weekCellClickCalendarPanel

Event handlers

27

Called when a date or date range is selected. If multiSelect is specified, this will fire upon deselection and selection of dates.

new DatePicker({
    onSelectionChange({ selection, oldSelection, userAction }) {

    }
});
ParameterTypeDescription
selectionDate[]

The selected dates. If multiSelect is specified this may be a two element array specifying start and end dates.

oldSelectionDate[]

The previously selected dates. If multiSelect is specified this may be a two element array specifying start and end dates.

userActionBoolean

This will be true if the change was caused by user interaction as opposed to programmatic setting.

onBeforeRefreshCalendarPanel
onCellClickCalendarPanel
onDateChangeCalendarPanel
onDestroyEvents
onFocusInWidget
onHideWidget
onPaintWidget
onRefreshCalendarPanel
onResizeWidget
onShowWidget
onWeekCellClickCalendarPanel

Typedefs

7

CSS variables

95
NameDescription
--b-date-picker-min-widthMin-width of the entire picker
--b-date-picker-title-font-weightFont weight for the title
--b-date-picker-day-font-sizeFont size for the day letters
--b-date-picker-date-paddingPadding for the date elements
--b-date-picker-date-font-sizeFont size for the date elements
--b-date-picker-today-font-weightFont weight for today's date
--b-date-picker-cell-margin-blockBlock margin for the date cells
--b-date-picker-toolbar-font-sizeFont-size for the top toolbar (that holds the navigation buttons + month/year)
--b-date-picker-day-colorDay letter color
--b-date-picker-date-colorDate color
--b-date-picker-today-backgroundToday's date's background
--b-date-picker-header-paddingDate picker's header padding, when configured to be shown
--b-date-picker-colorColor
--b-date-picker-today-colorToday's date's color
--b-date-picker-today-borderToday's date's border
--b-date-picker-toolbar-colorColor used on text and buttons in the date picker's top toolbar
--b-date-picker-selected-week-backgroundBackground for week containing the selected date, if configured to highlight it
Hovered
--b-date-picker-today-hover-backgroundToday's date's background when hovered
--b-date-picker-selected-hover-backgroundSelected date's background when hovered
--b-date-picker-date-hover-backgroundBackground for hovered date
Selected
--b-date-picker-selected-font-weightFont weight for the selected date
--b-date-picker-selected-week-border-radiusBorder-radius for the selected week
--b-date-picker-selected-colorSelected date's text color
--b-date-picker-selected-range-colorColor for dates in a selected range (excluding first/last)
--b-date-picker-selected-range-backgroundBackground for dates in a selected range (excluding first/last)
--b-date-picker-selected-backgroundBackground for selected date