16

How i can get keydown event on iframe?

pradeep
  • 1,047
  • 3
  • 20
  • 24
  • This answer works grate for me: http://stackoverflow.com/questions/26324213/listen-for-mouse-click-and-keypress-events-within-iframe/39617876#39617876 – Roy Shoa Sep 21 '16 at 13:30

3 Answers3

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
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