0

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?

Volomike
  • 23,743
  • 21
  • 113
  • 209

2 Answers2

1

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.

Alex
  • 8,875
  • 2
  • 27
  • 44
0

try this :

    var cancelClose=false; // This is a global variable

    $(document).ready(function(){
        $('input, textarea,select').each(
                function(){
                    $(this).focus(
                            function(){
                                cancelClose=true;
                            }
                        );
                    $(this).blur(
                            function(){
                                cancelClose=false;
                            }
                        );
                }
        );
    });

and then, on document key down event

say :

  if (cancelClose)
         return false;
Ahmad Hajjar
  • 1,796
  • 3
  • 18
  • 33