10

How can I trigger a click event from within an iframe to an element of its parent?

I tried the following code on the parent page before I open the iframe.

jQuery('iframe').contents().bind('eventhandler', function() {               
                alert('event was fired');
        }); 

I also tried

jQuery(document).bind('eventhandler', function(e) {
alert('event was fired');
}); 

and within the iframe I have embeded this code in a click event

jQuery(document).trigger('eventhandler');                      

but it does't work am I doing something wrong here?

themhz
  • 8,335
  • 21
  • 84
  • 109
  • Possible duplicate of [trigger click event in iframe parent window](http://stackoverflow.com/questions/3521947/trigger-click-event-in-iframe-parent-window) – Mark Schultheiss May 11 '16 at 17:11

2 Answers2

12

You need to refer to the parent document from the iframe. This should do what you need:

index.html:

<iframe src="iframe.html"></iframe>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function(){
    $(document).on('eventhandler', function() {               
        alert('event was fired');
    });
}); 
</script>

iframe.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function(){
    parent.$(parent.document).trigger('eventhandler');  
});
</script>
Dziad Borowy
  • 12,368
  • 4
  • 41
  • 53
  • ye its working thanx!, I hope I wont be having any trouble with IE or Chrome, I didn't test it yet. Only on firefox – themhz Aug 22 '12 at 19:15
  • if you run that from a server (apache or any other) it should work everywhere. The only problem will be in an unlikely event when iframe (and iframe content and jquery) will load before the parent jquery, but I assume you're not triggering the event "onload" as in my sample :-) – Dziad Borowy Aug 22 '12 at 19:22
  • no it works perfectly well. I add the first event on ready state , and then the second one on a button that is clicked within the iframe and works. thanx – themhz Aug 22 '12 at 19:26
  • 1
    @tborychowski you save my day bro.. :) – Jithin Raj P R Apr 12 '18 at 05:42
  • thank you very much, i test this function on chrome, it fire, thanks – Chung Nguyen Aug 03 '18 at 08:11
1

If you have control of the source for both, you can do it like this

How to communicate between iframe and the parent site?

Community
  • 1
  • 1
joevallender
  • 4,293
  • 3
  • 27
  • 35