views:

1825

answers:

1

Hi all,

I have an iframe on a page, coming from a 3rd party (an ad). I'd like to fire a click event when that iframe is clicked in (to record some in-house stats). Something like:

$('#iframe_id').click(function() {
    //run function that records clicks
});

..based on HTML of:

<iframe id="iframe_id" src="http://something.com"&gt;&lt;/iframe&gt;

I can't seem to get any variation of this to work. Thoughts?

+3  A: 

There's no 'onclick' event for an iframe, but you can try to catch the click even of the document in the iframe:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

$('#iframe_id').bind('click', function(event) { });
Traveling Tech Guy
Thanks, this works nicely, but only for content from my domain. If I try to load in 3rd party content from another domain, the click event doesn't fire. I've ran into some other posts on the web mentioning something similar...basically, you can play with iframe content, but only if its your own. I would definitely be dealing with only 3rd party content. Hmm, any other ideas?
Justin Lucente
Yes, actually. Try putting a transparent div on top of the iframe (use position: absolute). You can then catch clicks on that div. Don't forget to pass them down to the iframe (works only if it's a simple iframe content - if it contains its own even handling - don't use this method).
Traveling Tech Guy
Just to update: I've tried the absolute positioning, and all events were ignored if there was 3rd party content in the iframe. I don't think this one is going to happen, but I greatly appreciate the fact that you put forth some help.
Justin Lucente
No problem - that's what we're here for :) Sorry it didn't work out.
Traveling Tech Guy