views:

65

answers:

3

How to add a click event to <p> elements in iframe (using jQuery)

<iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">
A: 

Your best best bet is to invoke the iframe ASlONG as its part of your domain.

iframe.html

<html>
    <head>
        <script>
            window.MyMethod = function()
            {
                $('p').click();
            }
        </script>
    </head>
    <body></body>
</html>

And then use

document.getElementById('targetFrame').contentWindow.MyMethod();

To invoke that function.

another way is to access the iframe via wnidow.frames.

<iframe name="myIframe" src="iframe.html"/>

and the javascript

child_frame = window.frames['myIframe'].document;
$('p',child_frame).click(function(){
    alert('This click as bound via the parent frame')
});

That should work fine.

RobertPitt
Why the down vote ?
RobertPitt
A: 

By giving a reference to the IFrame document as the second parameter to jQuery, which is the context:

jQuery("p", document.frames["oframe"].document).click(...);
RoToRa
+1  A: 

There's a special jQuery function that does that: .contents(). See the example for how it's works.

jerone
Thanks, $('#iframe').contents().find('p').click()
faressoft