15

How can I attach a click event handler to an element inside an iframe?

Here's what I tried and doesn't work:

$("#parent iframe").contents().find("a").live("click", function () {
    alert ("test");
    return false;
});

The iframe is on the same domain.

Servy
  • 202,030
  • 26
  • 332
  • 449
Jourkey
  • 33,710
  • 23
  • 62
  • 78

2 Answers2

11

Discovered the problem. LIVE does not work inside an iframe. Switching to bind works fine. Will do manual event delegation instead.

Jourkey
  • 33,710
  • 23
  • 62
  • 78
  • 1
    Note this is far from the only problem you will have trying to script one window/frame with a copy of jQuery that lives in a different one. For anything complex, you will need to load copies of jQuery in both frames. jQuery is optimised for convenient single-window-scripting, not cross-window-scripting (which is inherently more complicated, jQuery or not). – bobince Nov 01 '09 at 00:42
0

Basically probably not as at a guess the content is likely to be from a different domain (usual use of iFrames). These articles explain why:

iframes and cross domain security Cross-Domain Ajax Insecurity

Alternatively you will need to modify the source code in the iFrame (if you have control over it) or you can ask users to reduce their browser security (might be possible on an intranet, but even then not a good idea).

FinnNk
  • 3,249
  • 23
  • 25