From 7fa0124fe25a53caa07c478e157dace3c4f2a6ee Mon Sep 17 00:00:00 2001 From: Sarah Vaupel Date: Thu, 14 Nov 2019 12:24:02 +0100 Subject: [PATCH] fix(datepicker): close datepickers on focusout or click outside --- frontend/src/utils/form/datepicker.js | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/frontend/src/utils/form/datepicker.js b/frontend/src/utils/form/datepicker.js index c6e6ff589..de7b0f6db 100644 --- a/frontend/src/utils/form/datepicker.js +++ b/frontend/src/utils/form/datepicker.js @@ -180,14 +180,27 @@ export class Datepicker { // change the selected date in the tail.datetime instance if the value of the input element is changed this._element.addEventListener('change', setDatepickerDate, { once: true }); - // close the instance on focus loss of the corresponding input element - // (only close the instance if source and target IDs differ, since interactions with the opened datepicker also triggers this event in some cases) - this._element.addEventListener('focusout', event => { - if (!event.relatedTarget || event.relatedTarget.id !== event.srcElement.id) + // close the instance on focusout of any element if the target is outside of the instance + window.addEventListener('focusout', event => { + console.log('focusout', event); + const targetIsOutside = !this.datepickerInstance.dt.contains(event.explicitOriginalTarget); + const targetIsNotTimepicker = !this.datepickerInstance.dt.contains(event.relatedTarget); + console.log(targetIsOutside, targetIsNotTimepicker); + if (targetIsOutside && targetIsNotTimepicker) + this.datepickerInstance.close(); + }); + + // close the instance on click on any element outside of the datepicker (except the input element itself) + window.addEventListener('click', event => { + const targetIsOutside = !this.datepickerInstance.dt.contains(event.target); + const targetIsInDocument = window.document.contains(event.target); + const targetIsNotInput = event.target !== this._element; + console.log(targetIsOutside, targetIsInDocument, targetIsNotInput); + if (targetIsOutside && targetIsInDocument && targetIsNotInput) this.datepickerInstance.close(); }); - // close the datepicker on escape keydown events + // close the instance on escape keydown events this._element.addEventListener('keydown', event => { if (event.keyCode === KEYCODE_ESCAPE) { this.datepickerInstance.close();