Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - stop a modal keyboard event from bubbling / propagating

I have a page which has a keydown event listener, to listen for the Escape key, to navigate back. I also have a simple modal class, which also listens for the Escape key to close it. The main page listener checks if a modal is open, and if so, returns without doing anything.

window.addEventListener("keydown", function (ev) {
                                           if (modal_is_open) { return; }
                                           ev = ev || window.event;
                                           if (ev.key == "Escape") { history.go(-1); }
                                         });

modal_div.addEventListener("keydown",function (ev) {
                                           ev = ev || window.event;
                                           ev.stopPropagation();
                                           ev.preventDefault();
                                           ev.cancelBubble = true;
                                           if (ev.key == "Escape") { close_the_modal(); }
                                           return false;
                                         });

My problem is, if a modal is open, the Escape key closes it, but still bubbles up to the main page handler and navigates back. How can I stop this?

like image 375
Iain Avatar asked Jul 03 '26 01:07

Iain


1 Answers

I finally found the solution, replace stopPropagation with stopImmediatePropagation, and the window keydown handler no longer fires if the modal is open.

like image 174
Iain Avatar answered Jul 05 '26 14:07

Iain