tags:

views:

1411

answers:

2

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;
});

Thanks.

Edit: the iframe is on the same domain.

A: 

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
It is on the same domain, but I'll thanks for saying it should work, i'll look at it again.
Jourkey
+1  A: 

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

Jourkey
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