Observer code: Wait an element to appear then do this

This code will let you do some magic when an element appears on the page. Let’s try using this on an iframe, let’s wait for an iframe to appear on the first box and then well get it’s source and display it to another iframe.

Let’s try adding the iframe 1 and as soon as the iframe 1 appears, the src should be put to iframe 2’s src. Try adding the iframe 1 by click the button below

Demo



Frame 1

Frame 2 (waiting for the iframe’s 1 src)

HTML

<button id="addbtn">Add iframe 1 src</button><br>
<b>Frame 1</b>
<div id="framecont"></div>
<br>
<b>Frame 2 (waiting for the iframe's 1 src)</b>
<iframe id="frame2" src="" width="100%" height="300"></iframe>

Script

<script>
var observer = new MutationObserver(function(mutations) {
    if ($('#frame1').length) {
        var frame1 = document.getElementById('frame1').src;
        document.getElementById('frame2').src = frame1;
        observer.disconnect(); 
        //We can disconnect observer once the element exist if we dont want observe more changes in the DOM
    }
});

// Start observing
observer.observe(document.body, { //document.body is node target to observe
    childList: true, //This is a must have for the observer with subtree
    subtree: true //Set to true if changes must also be observed in descendants.
});


//Add iframe src
$("button#addbtn").click(function(){
     $("#framecont").append('<iframe id="frame1" src="https://www.sapotdisenyo.com/wp-content/uploads/2020/09/sample-pdf.pdf#zoomFitW" width="100%" height="300"></iframe>');
});

</script>