themis themis - 2 months ago 14
jQuery Question

how to trigger a click event from within an iframe to an element of its parent?

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?

Answer

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>