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!

4
  • 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 Commented Apr 6, 2014 at 19:03
  • @PatrickEvans .load() is also used to handle the load event: api.jquery.com/load-event Commented Apr 6, 2014 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. Commented Apr 6, 2014 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. Commented Apr 6, 2014 at 19:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.