0

Similarly to this question Applying an onclick event to an element that doesn't exist on page load I am asynchronously loading an iFrame which I apparently can only style with javascript. However, I need to make some adjustments to the styling and therefore am trying to add an event to an element that is not there on page load. I figured that using the method in the answers to the aforementioned question, I could simply add a 'load' instead of a 'click' event.

    $('.widget-box').on('load','#iframeContainer',function(e){
        // my code
    });

This doesn't seem to work, however. Is there any other solution to my problem?

edit: as one of the commenters suggested, I used the mutation observer. It works now but doesn't seem very clean. If you have any suggestion for improvements, I'd be happy to hear.

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {

        (function($) {
            $('#okomoIframeContainer').load(function() {
                console.log('its loaded');
            })

        })(jQuery);
    });
});

observer.observe(widgetWrap, { childList: true });

edit2: Also, with this method I still can't modify the iframe's content because of the same-origin policy

  • 3
    Unfortunately, [the `load` event does not bubble](https://stackoverflow.com/questions/14983988/is-bubbling-available-for-image-load-events). You will have to attach the listener directly to the iframe container instead. What you can do, is that you attach the event listener as part of the logic that inserts the iframe. – Terry Jan 21 '19 at 13:45
  • 2
    Might also be able to use MutationObserver API – charlietfl Jan 21 '19 at 13:50
  • Do you have access to the async method that injects/writes the ` – Terry Jan 21 '19 at 14:27
  • yes i do have access but how do access an event from within an iframe? – Gabriel Roda Eugen Bach Jan 21 '19 at 14:37

0 Answers0