3

I have a page with an iframe.

<div id="my_content">
  <iframe id="my_iframe" src="http://mysite.com/iframe.html">
</div>

I need to intercept the click inside the iframe. I've tried with this code but it doesn't work:

<script type="text/javascript">


jQuery(document).ready(function(){
 jQuery('#my_iframe').click(function(){ 
  alert('click inside iframe');
 });
});
Pennywise83
  • 1,784
  • 5
  • 31
  • 44
  • I think jQuery code should be inside iframe. Then try to trigger something on iframe container. – sinsedrix Feb 17 '12 at 12:52
  • You've searched for it? Seems there are alot of replies on it. Like this one: http://stackoverflow.com/questions/6452502/adding-onclick-event-to-iframe – Asken Feb 17 '12 at 12:55

1 Answers1

5

Assuming that the iframe source is on the same domain as the outer page, you can use the contents method:

The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

jQuery(document).ready(function(){
  jQuery('#my_iframe').contents().click(function(){ 
    alert('click inside iframe');
  });
});
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • very very useful ! but do keep in mind that this snippet of code must be placed rite after the – atif Dec 26 '12 at 09:23
  • 1
    @atif, the above code can be placed anywhere within the page that contains the `iframe` - it needn't be directly after it. – Rich O'Kelly Dec 26 '12 at 15:16
  • 2
    well in my case it is not working if i place it in the heading of the page. Furthuremore, it needed me to refresh page once in order to make it working, so i added jQuery(window).load instead of document.ready – atif Dec 26 '12 at 15:41
  • 1
    @atif, apologies. In my previous comment I meant anywhere within the body of the page that contains the iframe. – Rich O'Kelly Dec 26 '12 at 16:28
  • it is not working for me also. – Kshitij Verma May 02 '22 at 08:21
  • Hi @KshitijVerma, can you post an example of your code that's not working (in another question) and I'll happily take a look; but the above code snippet will work (assuming that jQuery is loaded, the "#my_iframe" is a suitable locator for the iframe and the iframe source is on the same domain as the outer page. – Rich O'Kelly May 03 '22 at 16:19