Pass jquery variables between iframe and parent
How can I work with jQuery and iframe
. Get and pass var
from iframe
to body
and from body
to iframe
. I have the following example. How can I click the button in iframe
and make it take effect on the the body
#test
. How about ready var x in iframe.
<body>
var x = "whatever";
<div id"test"></div>
<iframe width="200px" height="200px" src="page.html"></iframe>
</body>
Inside page.html i have
<button>clickme</button>
<script>
var elm = $('<span>content</span>');
elm.appendTo('#test')
</script>
Solution 1:
$("#myid", top.document);
or
$("#myid", parent.document.body);
This will give you access to the container of the IFRAME
as per : http://groups.google.com/group/jquery-en/browse_thread/thread/5997ef4a60a123af
Solution 2:
From the parents perspective:
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();
OR
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;
From the iframe perspective
<script type="text/javascript">
var myLocalVariable = "hello";
function myLocalFunction () {
return "hello";
}
</script>
Solution 3:
You can use contentWindow
and contentDocument
properties, if same origin poilicy is not a problem. I've setup a demo. View code for the demo and code for iframe.