How i can get keydown event on iframe?
Asked
Active
Viewed 2.5k times
3 Answers
21
You need to access the document of the iframe which is through the ContentWindow object
$(document.getElementById('IFrameId').contentWindow.document).keydown(function(){ alert('Key down!'); });
Make sure you bind the event after the frame has loaded.

James
- 80,725
- 18
- 167
- 237
-
@Aksival Of course, have been racking my brain wondering why this doesn't work for ages now. – Ally Nov 01 '12 at 15:04
-
1@RedHouse I have updated the answer to clarify that point (I thought that Aksival's comment would have been clear for people to see) – James Nov 02 '12 at 09:15
-
Here's a way of binding after load document.getElementById('IFrameId').onload = function(){ as above }; – paulmorriss Oct 28 '13 at 15:38
-
5
Adding event handler to an iframe using JQuery
$(document.getElementById('iframe_id').contentWindow.document).keydown(function() {
// my func
});

Community
- 1
- 1

Ahmed Atia
- 17,848
- 25
- 91
- 133
-
6`$("#iframe_id").get(0).contentWindow.document` is equivalent to `$(document.getElementById('iframe_id').contentWindow.document)` – BrunoLM Jul 24 '11 at 23:58
1
It's so late to answer but maybe is useful for somebody .
I've same problem,that means I've an iframe inside a HTML
page in a same domain
.
Now I need to get the Esc keyup event
.
however I don't want (or some times I can't) to write any script inside iframe body.
to do it, I use below script to detect what is the parent id of element that selected by clicked on it.
$(window).load(function () {
jQuery(jQuery('[id="frame"]')[0].contentWindow.document).on('keyup', function (e) {
var _currntItem = ($(e.target))
if (e.keyCode === 27) {
alert(_currntItem.parent().attr('id'));
}
});
This code resolved my problem.
hope to useful.

Hamid Talebi
- 1,298
- 2
- 24
- 42