Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass jquery variables between iframe and parent

Tags:

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>
like image 784
Hussein Avatar asked Jan 14 '11 08:01

Hussein


3 Answers

$("#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

like image 200
LiamB Avatar answered Oct 15 '22 15:10

LiamB


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>
like image 24
sparkyspider Avatar answered Oct 15 '22 15:10

sparkyspider


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.

like image 40
Salman A Avatar answered Oct 15 '22 14:10

Salman A