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?
you can call parent. functionname() from your iframe. what if parent window is in different domain, then cannot raise events on parent window from child iframes.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
onClick HTML attribute does not work at all, the handler is not called.
Answer: Use the jQuery contents() method If you try to detect or capture a click event inside an iframe simply using jQuery click() method it will not work, because iframe embed a web page within another web page. However, you can still do it on the same domain utilizing the jQuery contents() and load() method.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With