diff --git a/README.md b/README.md index 294ebec..33757a7 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,20 @@ datePicker(selector, options, { } }); ``` + +### onDateSelect + +A callback that accepts a Date object when a date is selected via the date picker. + +Using it in your code: +```javascript +datePicker(selector, options, { + onDateSelect: function(selectedDate) { + // do something with selected date + } +}); +``` + ## Running locally Clone this repository to your local machine and install dependencies. diff --git a/src/__tests__/datepicker.test.js b/src/__tests__/datepicker.test.js index 5aca10b..7c60e03 100644 --- a/src/__tests__/datepicker.test.js +++ b/src/__tests__/datepicker.test.js @@ -1059,5 +1059,30 @@ describe('Date picker', () => { expect(highlighted === document.activeElement).toBeTruthy(); }); + + it('should call the onDateSelect callback with the selected date', () => { + let expectedDate; + + datePicker( + document.querySelector('.date-picker'), + {}, + { + onDateSelect: (date) => { + expectedDate = date; + }, + }, + ); + + const revealButton = document.querySelector('.date-picker__reveal'); + + $(revealButton).trigger('click'); + + const todayButton = document.querySelector(`[data-test-id="${today.toLocaleDateString()}"]`); + $(todayButton).trigger('click'); + + expect(expectedDate.getDate()).toEqual(today.getDate()); + expect(expectedDate.getMonth()).toEqual(today.getMonth()); + expect(expectedDate.getFullYear()).toEqual(today.getFullYear()); + }); }); }); diff --git a/src/js/datepicker.js b/src/js/datepicker.js index ce927bc..e53e6f3 100644 --- a/src/js/datepicker.js +++ b/src/js/datepicker.js @@ -166,6 +166,10 @@ function datePicker(datePickerElement, options = {}, callbacks = {}) { elements.inputs.day.value = formatDateInput(date.getDate()); elements.inputs.month.value = formatDateInput(date.getMonth() + 1); elements.inputs.year.value = date.getFullYear(); + + if (callbacks.onDateSelect) { + callbacks.onDateSelect(date); + } } function setIsPreviousEnabled() {