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"></iframe>
I can't seem to get any variation of this to work. Thoughts?
There's no 'onclick' event for an iframe, but you can try to catch the click event 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').on('click', function(event) { });
Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.
Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.