2

In jquery, I want to do this basically:

$(window).on('load', 'iframe', function() {
    alert(this);
});

Is this possible to do? I want to run a function anytime a iframe is dynamically added to DOM and it finishes loading.

Cœur
  • 37,241
  • 25
  • 195
  • 267
omega
  • 40,311
  • 81
  • 251
  • 474

2 Answers2

0

When a new iframe is dynamically added to DOM you also have to dynamically create a new event handler function to it. It is the rule and nothing can change that.

Tommy Nguyen
  • 96
  • 1
  • 5
0

Well, I believe this can be achieved with the combination of MutationObserver and jQuery's event bindings.

You can register the observer to the DOM like this (sample code borrowed from here):

$(function() {
  var target = document.querySelector('body');

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      // Check if nodes are added
      if (mutation.addedNodes.length > 0) {
        mutation.addedNodes.forEach(function(node) {
          // Check if the added node is an iframe
          if (node.nodeName === "IFRAME") {
            $(node).on("load", function() { alert("hello from iframe"); });
          }
        });
      }
    });
  });

  // configuration of the observer (need to research more on this)
  var config = {
    attributes: true,
    childList: true,
    characterData: true
  };

  // pass in the target node, as well as the observer options
  observer.observe(target, config);
});

The above will observe the changes in DOM, and will check the added elements to the DOM dynamically.

I believe you can leverage this feature to bind the event on runtime to the added iframes like I did above.

Just don't forget to unobserve after you're done with this:

observer.disconnect();
31piy
  • 23,323
  • 6
  • 47
  • 67