0

I have a modal which I want to close when user pressed the Escape key. However, this modal also contains form fields that may benefit from default behaviours from the browsers.

For exemple an opened <select> element will close when hitting the Escape key. If this happens I don't want to close the modal since I consider the user wanted to close the <select> when hitting Escape. However, when it is already closed, I want the modal to close.

The question is: Is there a way to know whether a default event was fired or not?

It seems the defaultPrevented property is called whenever preventDefault() was, whether or not it actually prevented something.

CCR
  • 154
  • 4
  • 18

1 Answers1

0

Closing modals is no default event, so you have to make use of event.stopPropagation(). You just have to add event.stopPropagation() on the selects keydown event, to prevent the Escape button from closing the modal.

You should check out the difference between event.preventDefault() and event.stopPropagation() and stopPropagation vs. stopImmediatePropagation.

Christopher
  • 3,124
  • 2
  • 12
  • 29
  • I understand that `event.stopPropagation()` would help me. However, how do I call this method only in the case that there actually was a default event triggered. Say my ` – CCR Apr 12 '21 at 09:18
  • You can't check if the default-select-dropdown is open or not. (maybe with some handlers, but it won't be 100% accurate) - You could also just tab in it and press up/down-arrow keys to select something. - You can make use of the bubbling phase and watch the same event on two different nodes (select and it's parent node) and check on both if event.defaultPrevented is false/true. If it's still false on the parent the default-browser-event was executed. – Christopher Apr 12 '21 at 09:31