Frankie
Frankie

Reputation: 25165

document and iframe in just one selector

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");
    });     

});

Upvotes: 1

Views: 410

Answers (2)

Tom
Tom

Reputation: 7091

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/

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630469

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.

Upvotes: 3

Related Questions