Search code examples
jquerykeydownevent-bubblingesc-key

Capturing Esc Key with jQuery on Document, but Not Contents


Imagine an HTML form and the jQuery library is loaded. I'd like it such that if someone is not currently focused on a form field, and they click the Esc key, a dialog pops up to ask if they want to close the form window (because the form window opened as a new tab).

If I try to capture it on $(document), the trouble I have is with event bubbling where the fields pick this up, so an Esc key press in a field causes the event to fire.

How can I efficiently (key word) prevent the event bubble and capture when Esc is pressed when no fields have the focus?


Solution

  • You'll have to use an If statement to check that none of the inputs have focus:

    if ($('input').is(":focus")){ ... }

    In my example i use the enter key press to check for focus.

    Hope this helps.