How to capture click event with jquery for iframe?

Member

by jerad , in category: Javascript , 10 months ago

How to capture click event with jquery for iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 10 months ago

@jerad 

To capture a click event within an iframe element using jQuery, you can use the contents() method to access the document inside the iframe and then bind a click event handler to it. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$(document).ready(function() {
  // Get the iframe element by its id
  var iframe = $('#your-iframe-id');

  // Bind a click event handler to the iframe document
  iframe.contents().find('body').on('click', function() {
    // Handle the click event here
    alert('Click event captured within the iframe!');
  });
});


Replace 'your-iframe-id' with the actual id of your iframe element. The contents() method allows us to access the document within the iframe, and then we use find('body') to target the body element inside the iframe. Finally, the on('click') method is used to bind the click event handler to the iframe's body element.


Remember to replace the alert() function with your desired code or logic to handle the click event within the iframe.