Reputation: 8424
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?
Upvotes: 10
Views: 17295
Reputation: 4293
If you have control of the source for both, you can do it like this
How to communicate between iframe and the parent site?
Upvotes: 1
Reputation: 12579
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>
Upvotes: 12