简体   繁体   中英

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

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>

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');
     });
   });
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM