1

So, I'm trying to get an element inside of an iframe srcdoc using jQuery/javascript, and say, attach a click handler. e.g..

<iframe id="iframe" srcdoc="<html><head></head><body><input type="button" id="button" /></body></html>"></iframe>

The following code does not work:

$("#iframe").find("#button").on("click", function{ alert('clicked'); });

Nor does using $("#iframe").contents() or several other methods.

How can I attach event handlers to elements inside an Iframe srcdoc?

MouseTech
  • 110
  • 2
  • 8
  • I believe jQuery's `.contents()` function will grab the HTML inside an iFrame's `srcdoc` attribute just as it would if that HTML were nested inside of the tags. You will be interested in this question: http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe (perhaps rendering this question a duplicate?) – Matthew Vita Aug 30 '15 at 12:01
  • also, your JS is a bit malformed. You'll need to append `()` after `function` in your callback. – Matthew Vita Aug 30 '15 at 12:03

1 Answers1

1

JS to handle click :

$("#iframe").contents().find("body").find("#button").click(function() {alert('clicked')});

HTML changes :

<iframe id="iframe" srcdoc="<html><head></head><body><input type='button' id='button' /></body></html>"></iframe>

EDIT: load iframe using JS :

$("#container").append($("<iframe />").attr({"srcdoc":"<html><head></head><body><input type='button' id='button' /></body></html>", "id":"iframe" })); 

$("#iframe").load( function() {
    $("#iframe").contents().find("body").find("#button").click(
        function () {alert('clicked')}
    );
});

working Fiddle link : http://jsfiddle.net/hufrmcLt/

EDIT : http://jsfiddle.net/hufrmcLt/1/

Dipali Vasani
  • 2,526
  • 2
  • 16
  • 30
  • This seems like it should work, but it doesn't. Is it because of the way I'm appending the container element to the dom, then immediately attaching event handlers? – MouseTech Aug 30 '15 at 12:30
  • ` $(".container").append($("").attr({"srcdoc":"", "id":"iframe" })); $("#iframe").contents().find("body").find("#button").click(function () { alert('clicked'); });` – MouseTech Aug 30 '15 at 12:31
  • The way you are appending iframe is the issue, when the iframe is not appended the event is trying to get bind to button(it's actually not there in body) – Dipali Vasani Aug 30 '15 at 12:35
  • So is it a timing issue? What's a better way to accomplish this? – MouseTech Aug 30 '15 at 12:41