Is it possible to trigger an event on dynamically loaded iframe contents in a document with jquery: on method

1.7k Views Asked by At

I would like to add mousemove and keypress events for iframes. The following code works for existing iframes in the page but it won't for dyanamically created frames in the document through javascript.

$('iframe').contents().keypress(function(){
         console.log('iframe keypress event fired1');
      });

      $('iframe').contents().mousemove(function(){
        console.log('iframe mousemove event fired2');
     });

I wanted to make this work for dynamically created frames after document is loaded. I have copied entire code below.

<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Iframe Events Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
</head>
<body>
<div>Existing Iframe</div>
<input id="btnFrame" type="button" value="Load Dynamic Iframe"/>
<iframe width="200px" height="100px"></iframe>
</body>
<script>

$(document).ready(function() {
    console.log('document ready event...');
    $('#btnFrame').click(function(){
        console.log('btn click event...');
        console.log($('iframe#dynamic').length);
        if ($('iframe#dynamic').length === 0) {     
            prepareFrame();
        }       
    }); 
});

$(window).on('load', function() {
       $('iframe').on("load", function () {
         // All the contents of the iframe are loaded
         $('iframe').contents().keypress(function(){
            console.log('iframe keypress event fired');
         });
       });
    });


function prepareFrame() {
    var ifrm = document.createElement("iframe");
    ifrm.setAttribute("id", 'dynamic');
    ifrm.style.width = "640px";
    ifrm.style.height = "480px";
    document.body.appendChild(ifrm);
}

</script>

</html>
2

There are 2 best solutions below

6
Senal On

This is because your iframes are not available when you are registering the event listener. You can register your event listener after your view done loading.

$(window).on('load', function() {
   $('iframe').on("load", function () {
     // All the contents of the iframe are loaded
     $('iframe').contents().keypress(function(){
        console.log('iframe keypress event fired');
     });
   });
});
0
Bansi Patel On

Better approach to get click event using JS First Get element of Iframe

 const iframe = document.getElementsByTagName('iframe')[0];

Then add one Anchor tag having Id as 'play_video' in HTML and add click event

const play = document.getElementById('play_video');
play.click();

That's how you will get an event on click of Iframe which dynamically loaded from CMS or Database.