3

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>
Tasos
  • 1,622
  • 4
  • 28
  • 47
  • works for me when both documents are located on the same domain: http://jsfiddle.net/doktormolle/Q7QuW/1/ – Dr.Molle Aug 22 '13 at 10:59
  • 1
    Does this answer your question? http://stackoverflow.com/a/5976237/779092 Note: you're going to want to run our code in the iframe's `onload` event, rather than the current document's event. – Shea Aug 22 '13 at 11:00
  • I was testing it in jsfiddle with my sites url so that's why it wasn't working. But now it works on my domain, thank you. – Tasos Aug 22 '13 at 11:02

1 Answers1

3

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.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • 1
    The iframe is located on my domain though, and so is the contact form php file, I still can't access it? – Tasos Aug 22 '13 at 10:56
  • I was testing it in jsfiddle with my sites url so that's why it wasn't working. But now it works on my domain, thank you. – Tasos Aug 22 '13 at 11:03
  • that's what i was thinking that's why i mentioned on the top `you can't apply jQuery to other domain iframes. It's blocked due to security.` – Tushar Gupta - curioustushar Aug 22 '13 at 11:04