0
votes

I have a page that has dynamically added iFrames in it. I want to catch the "onLoad" event for every iFrame.

So basically, I want to attach the event to the body but have it apply to every child iFrame. This works for other events, but it seems like the "load" event isn't propagating.

Here's what I've tried so far:

$(document).on("load", "iframe", function() {
	$("body").append("this is what I want, but it doesn't work!");
});

var iFrame = $("<iframe/>", {
        srcdoc  : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>"
});

$("body").append(iFrame);

iFrame.on("load",function(){
	$("body").append("this seems to work.... but isn't what I'm looking for.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

and here it is on jsfiddle: https://jsfiddle.net/skeets23/qsrf802z/8/

Any way to get this working as expected? So I can just create one binding and have it work for any number of dynamically added iFrames?

2
@peeebeee no, I wish it was that easy. Quoting my question: "This works for other events, but it seems like the "load" event isn't propagating."Skeets
Yeah, I withdrew my flag.peeebeee

2 Answers

1
votes

Seems you want to add iframe dynamically, so, best method is catch event DOMNodeInserted of document. See example follow:

$(document).on('DOMNodeInserted', function(e) {
    //check is iframe is loaded
    if(e.target.localName=="iframe"){
      console.log("New iframe loaded!");
      $("div").append("this does NOT seem to work!");
    };
});
function addIframe(){
    var iFrame = $("<iframe />", {
            srcdoc  : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>"
    });
    $("body").append(iFrame);
    iFrame.on("load",function(){
      $("div").append("this seems to work....");
    });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button onclick="addIframe();">Add Iframe</button>
    <div>

    </div>
0
votes

Change $(document).on("load" ... to $("iframe").on("load", .... And place it at end of script, it will work!

var iFrame = $("<iframe />", {
        srcdoc  : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>"
});

$("body").append(iFrame);

iFrame.on("load",function(){
	$("div").append("this seems to work....");
  //alert("cde");
});
$("iframe").on("load", function () {
	$("div").append("this does NOT seem to work!");
  alert("abc");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>

    </div>