tobby
tobby

Reputation:

Adding event handler to an iframe using JQuery

I want to assign a keydown event handler to an iframe. Something similar to the pure JS:

document.getElementById('iframe_id').contentWindow.addEventListener('keydown',funcName, true);

I tried:

$(document.getElementById('iframe_id').contentWindow).keydown( function() {
   // my func
});

But it does not work.. Please help!

Upvotes: 9

Views: 25048

Answers (4)

Larry
Larry

Reputation: 41

This worked for me:

$('#iframe_id').contents().keydown(function() {
    // my func
});

Upvotes: 0

Mcbeev
Mcbeev

Reputation: 1529

The $ function replaces the need for document.getElementById

$('iframe_id').contentDocument.keydown(function() {
   // logic
});

Upvotes: 0

arxpoetica
arxpoetica

Reputation: 5071

Just something to keep in mind: this will never work, as far as I understand, if the iframe content is cross-domain. You'll end up with permissions errors: Permission denied for http://... to get property HTMLDocument.nodeType from http://.... Browsers limit parent child dom permissions to same domain.

Upvotes: 4

Crescent Fresh
Crescent Fresh

Reputation: 116980

contentWindow is the iframe's window object. You want the iframe's document instead:

$(document.getElementById('iframe_id').contentWindow.document).keydown(function() {
    // my func
});

Note that I am not sure how jQuery reacts to elements from other windows/frames.

Upvotes: 15

Related Questions