Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 826
themhz Avatar asked Aug 22 '12 18:08

themhz


People also ask

How do I pass an iframe event to parent?

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.

How do you trigger a click element?

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.

Does onClick work on iframe?

onClick HTML attribute does not work at all, the handler is not called.

How do I click an iframe event?

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.


1 Answers

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>
like image 89
Dziad Borowy Avatar answered Oct 07 '22 04:10

Dziad Borowy