Search code examples
javascripteventsiframedom-events

Make an iFrame trigger the body.onclick event


I have a script that attaches a function to be triggered by the the document.onclick event. The problem is that the page has an iframe in it. When the user clicks on the iframe, the document.onclick event does not trigger the function attached to it. Is there any way to fix this? In rare cases, the iframe may have another iframe inside of it as well that must also trigger the event.

Note: I am not using jQuery. It's a great tool, but it is not the optimal solution this overall project.


Solution

  • Try ...

    console.log(window.parent.document);

    ... from within the iFrame.

    If that works (you see it logged in the firebug console as an object) it's just a matter of finding the iframe element and attaching a click event to it.

    var parent = $(window.parent.document);
    // I'm using "iframe" but you'll need to find a more accurate selector.
    $('iframe', parent).click(function(){
       alert('clicked');
    });