2

I'm trying to fire a click event on the click of an element inside an iframe, but it doesn't seem to be working. My current set up:
jsFiddle: http://jsfiddle.net/q4aa3/
jQuery:

$(document).ready(function () {
    $('#this-iframe').load(function () {
        $('#this-iframe').contents().find('img').live({
            click: function () {
                alert('clicked img');
            }
        });
    });
});

Clicking on the image inside the iframe isn't firing the alert, I'm not sure why, or is there a better way to achieve this? Any suggestions would be greatly appreciated!

user1374796
  • 1,544
  • 13
  • 46
  • 76
  • 1
    the iframe contains a page from a different domain,in this case the jsfiddle result frame is loaded from `fiddle.jshell.net` and your iframe is loading `jsfiddle.net` which means they are different domains so you do not have access to it. Also jQuery's `.load` function loads in data from a url, it is not a onload event. [jQuery load docs](http://api.jquery.com/load) – Patrick Evans Apr 06 '14 at 19:03
  • @PatrickEvans `.load()` is also used to handle the load event: http://api.jquery.com/load-event/ – Jason P Apr 06 '14 at 19:10
  • @PatrickEvans yes I understand that, the jsFiddle is just a demo of my setup. The domain I'm using this on, the iFrame content is also from the same domain, thus I have access to it. But this click function still isn't working. – user1374796 Apr 06 '14 at 19:16
  • @JasonP Ahh I see. user1374796, even though there is a load event available, it does not get called on iframes so you will need some other method to know when the page is loaded. – Patrick Evans Apr 06 '14 at 19:20

1 Answers1

10

When you have the iframe on the same domain, you can use this script to catch clicks in the iframe. Don't use .live, it is depriciated as of jQuery 1.7.

var iframeBody = $('body', $('#iframe')[0].contentWindow.document);
$(iframeBody).on('click', 'img', function(event) {
    doSomething();
});

You can manipulate the body through the iframeBody variable.

Ivotje50
  • 518
  • 7
  • 15