Attach event to iframe element in parent code

In my application, I have an iframe, and I would like to give it access to some functionality that changes the state of the application outside the iframe. This function should be triggered by the keydown event inside or outside the iframe.

In the iframe, I have the following code:

 window.init = function (api) { api.bind(document); }; 

And the external application does something like:

 iframe.contentWindow.init({ bind: function (element) { $(element).bind('keydown', function () { debugger; }); } }); 

In this case, init is called correctly, but the keydown event keydown never called. What am I doing wrong?

+4
source share
2 answers

The problem is that some part of the iframe has already bound a keydown handler, which stops the event from propagating, preventing the event from reaching the document and preventing the handler from being called. Nothing happened with the actual binding.

0
source

If you are trying to bind an event this way:

  $(element).bind('keydown', function () { alert("hello"); }); 

jquery will try to cross your element in the parent window , but if you do the following, your problem will be solved:

  $(iframe.contentWindow.document.body).find(element).bind('keydown', function () { alert("hello"); }); 
+4
source

All Articles