views:

20

answers:

2

I am currently injecting an iframe and binding a keyevent both to the document and the iframe.

Can I select both the iFrame and the document in one row?
notice the iframe must have .contents() after the selector

// wait for iframe to load
$('iframe#iframe').load(function() {

    // event bind to document
    $(document).bind('keydown', function(e) {
        console.log("runs document");
    });

    // event bind to iframe
    $(this).contents().bind('keydown', function(e) {
        console.log("runs iframe");
    });     

});
+3  A: 

You can use .add(), like this:

$(this).contents().add(document).keydown(function(e) {
    console.log("runs in both");
});   

This takes the iframe contents then just adds the document on the returned jQuery object as well, resulting in both being having the handler to their keydown event.

Nick Craver
@Nick Took you about 2m to solve something I was running around for more than 20! ;) 7 more minutes to accept. Thks Nick.
Frankie
+1  A: 

How about this:

// wait for iframe to load
$('iframe#iframe').load(function() {

    // event bind to iframe
    $(this).contents().add(document).bind('keydown', function(e) {
        console.log("runs iframe and document");
    });     

});

See http://api.jquery.com/add/

Tom
There's no reason to wrap a jQuery object in a jQuery object :)
Nick Craver
@Tom, thks for the idea! Was also good!
Frankie
Oh, wow. Didn't even notice, thanks.
Tom