Search code examples
javascriptflatpickr

How can I add a double click event on a flatpickr-day element


I have some flatpickr calendars with day and time, and I want to close the calender when I double click on a flatpickr-day element in the calendar.

I tried to add a double click listener in the flatpickr options, the onOpen field

var flatpckr_options = {
        enableTime: true,
        altInput: true,
        altFormat: "d-m-Y H:i",
        dateFormat: "Y-m-d H:i", 
        time_24hr: true, 
        allowInput: true,
                onOpen: function(selectedDates, dateStr, instance) {
    [...instance.calendarContainer.querySelectorAll(".flatpickr-day")].map(x => x.addEventListener('dblclick', function (e) {
              calendars.map(x => x.close());
              console.log("double click");
            }));

        }
    };
    const calendars = flatpickr(".calendar", flatpckr_options);

https://jsfiddle.net/p3e0da6r/2/

however the double click event doesn't get triggered on the flatpickr-day element, how can I get it to work?

I think it's because once I click on a day it changes focus to the flatpickr-time element, if I didn't have the time element the calendar would close on single click inside a flatpickr-day element by default, but I do need the time element as well.


Solution

  • A less than perfect solution, but gets the job done for what I need right now:

    var new_date = 0, old_date = 0;
    
    // ... inside the flatpickr options, for the onChange event
    
    onChange: function(selectedDates, dateStr, instance) {
                    old_date = new Date();
       [...instance.calendarContainer.querySelectorAll(".flatpickr-day")].map(x => x.addEventListener('mousedown', function (e) {
                        new_date = new Date();
                        let diff = new_date - old_date; // in ms < 500ms => double click
                        if (diff <= 500) {
                            calendars.map(y => y.close());
                        }
                        old_date = new_date;
                    }));
                },