How to add click event to a iframe with JQuery

Viewed 178434

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?

12 Answers

Maybe somewhat old but this could probably be useful for people trying to deal with same-domain-policy.

let isOverIframe = null;
$('iframe').hover(function() {
        isOverIframe = true;
    }, function() {
        isOverIframe = false;
    });

$(window).on('blur', function() {
    if(!isOverIframe)
        return;

    // ...
});

Based on https://gist.github.com/jaydson/1780598

You may run into some timing issues depending on when you bind the click event but it will bind the event to the correct window/document. You would probably get better results actually binding to the iframe window though. You could do that like this:

    var iframeWin = $('iframe')[0].contentWindow;
    iframeWin.name = 'iframe';
    $(iframeWin).bind('click', function(event) {
        //Do something
        alert( this.name + ' is now loaded' );
    });

You can solve it very easily, just wrap that iframe in wrapper, and track clicks on it.

Like this:

<div id="iframe_id_wrapper"> <iframe id="iframe_id" src="http://something.com"></iframe> </div>

And disable pointer events on iframe itself.

#iframe_id { pointer-events: none; }

After this changes your code will work like expected.

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

Related