Liron Harel
Liron Harel

Reputation: 11247

iFrame Click event not fired

How to catch click on an iframe using JQuery. I have an Amazon banner, and I need to close its container DIV when the user clicks the iframe. I've tried 'contents', onclick on iframe, binding the event but nothing works. When I click the iframe it opens Amazon's page on another tab, but the click event never fires. I put a breakpoint and alert just to make sure.

I am using latest JQuery version 1.9 and tested it on Chrome. I also thought about capturing a global click ($(document).click) and check the area of the click, but when I click the iframe, $(document).click doesn't fire. Any suggestions?

Again, it's an Amazon banner iframe, it's hosted on Amazon not on my server.

Example of the regular on binding that doesn't work: http://jsbin.com/oyanis/4/edit

Upvotes: 4

Views: 5778

Answers (1)

Julian Hille
Julian Hille

Reputation: 669

There is a neat trick to get a "click" on on iframe content.

You could do:

<div id="iframeinside">
    <iframe />
</div>

This now makes it possible to say in js something like:

 var oldActive = document.activeElement; /* getting active Element */
 var frame = $('#iframeinside iframe')[0];
 $('#iframeinside').mouseenter(function() {
      /* Setting interval to 1ms for getting eventually x,y mouse coords*/
      oldActive = document.activeElement;
      setInterval('doSomething()', 1); 
 });

 $('#iframeinside').mouseleave(function () {
      /* clear interval cause we arent over the element anymore*/
      clearInterval(intervalId); 
 });

These intervals do call:

function doSomething() {
    /* if the focus has changed to the iframe */
    if(oldActive != frame && document.activeElement == frame) {
        oldActive = document.activeElement;
        alert(myQuery);
        alert('click did happen to the iframe');
    }
}

I used this for several things and it always worked. What i didnt check was how about ie6,7 and older brothers.

Upvotes: 4

Related Questions