Tasos
Tasos

Reputation: 1642

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>

Upvotes: 3

Views: 15471

Answers (1)

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.

Upvotes: 3

Related Questions