Search code examples
jqueryiframekeydown

How to hide an iframe on keydown using jquery


I've got an iframe that I want to hide when I type ESC. I've also got two pieces of code which I can place in $(document).ready(). The first works, the second doesn't. Seems to me that they should both hide an iframe if the ESC key is pressed in it. What am I missing?

Works:

$(document).keydown(function(e) {
    if ( //e.keyCode == 13 ||     // enter
        e.keyCode == 27) {     // esc
        $(document).find(".popup").hide();
    }  
});

Doesn't work:

$(document).find(".popup").keydown(function(e) {
    if ( //e.keyCode == 13 ||     // enter
        e.keyCode == 27) {     // esc
        $(this).hide();
    }  
});

The iframe has the class popup.


Solution

  • The first case works because "document" can interpret key events, the "document" as a jQuery selector is always an active event listener, but the element with class .popup isn't. If you look for the .popup element before the key event ... you're placing it as the selector, but that element is never listening to any key event.

    To better understand the concept .. check the following jsFiddle Demo

    $(document).find(".popup").keydown(function(e) {
         if (e.keyCode == 27) { 
             alert();
         }  
    });
    

    Notice that if you use an input, select it and press ESC it will launch the alert box. On another hand, if you comment the input and use the div element instead it will never launch the alert box because it is never selected and listening to anything.

    BUT (there's always a but) ...

    If you want a div or another "deaf" element to listen to key events you can add tabindex="0" to the element and give it focus before binding the key event like this:

    See jsFiddle Demo

    HTML

    <div class="popup" tabindex="0"></div>
    

    JQuery

    $(document).find(".popup").focus().keydown(function(e) {
         if (e.keyCode == 27) { 
             alert();
         }  
    });