Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery not working on iframe content

I am trying to apply css to a label when input fields are focused using jQuery, but it doesn't seem to work. The contact form is loaded inside an iframe. If an iframe is not used, it works fine - check this jsfiddle: http://jsfiddle.net/nN3w2/ (if the iframe doesn't load the server might gone down - but the code is there for you to see).

The iframe and the contact form are located on the same domain. The contact form is included using php to my website.

<script type="text/javascript">
jQuery(document).ready(function($) {
    $("#iframe").contents().find("input").focus(function() {
        $("#iframe").contents().find("label").css('opacity','0');
    });
});
</script>

non-iframe

<script type="text/javascript">
jQuery(document).ready(function($) {
    $("input").focus(function() {
       $("label").css('opacity','0');
    });

    $("input").focusout(function() {
         if($("input").val() ==="" ) {
           $("label").css('opacity','1');
        }
    });

});
</script>
like image 378
zefs Avatar asked Jan 31 '26 10:01

zefs


1 Answers

Not possible

you can't apply jQuery to other domain iframes. It's blocked due to security.

Expanding on "not possible"...

The "Same origin policies" apply: your only way of communicating with the contents of iframes that come from another [domain|subdomain|protocol|port] is through the postMessage API, which of course requires the other part (the document inside the iframe) to listen to your messages.

Update after OP's Comment

Perhaps you can do something like this

$('#iframeOne', window.parent.document);

Another way to do it

window.parent.$("#iframeOne");

Another way

$("#iframeOne", top.document);

If you know the name of the parent window, you can also do

$("#iframeOne",opener.document)

Here opener is the name of the window.

like image 138
Tushar Gupta - curioustushar Avatar answered Feb 02 '26 01:02

Tushar Gupta - curioustushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!