Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$ is not defined in iFrame

Tags:

jquery

iframe

I have a page with an iframe in it. my iframe page is iframe.php and my main page is main.php when i load iframe.php directly my jquery code executes fine, but when I load main.php (which contains iframe.php as an iframe) I get an error "$ is not defined".

could this be because both main.php and iframe.php use

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

if so how can I use jquery in the iframe page without including this line?

like image 987
Devin Crossman Avatar asked May 13 '11 03:05

Devin Crossman


2 Answers

I figured it out. In the iFrame I used

var $ = parent.$;

as well as giving any jquery calls the document for context. ie

$("#element", document).doStuff();

It's weird because the original way I had it (with jquery included in both pages) worked fine in Safari for Mac but in Firefox it gave me the error

Error: c.defaultView.getComputedStyle(h, null) is null Source File: http://code.jquery.com/jquery-latest.pack.js Line: 16

like image 105
Devin Crossman Avatar answered Sep 18 '22 17:09

Devin Crossman


I was loading iframe in a webpage and I could find $ object using

var $ = parent.$;

but this was not performing selection on the elements of iFrame. Found below code to execute selector on the iFrame body

if (typeof(jQuery) == "undefined") {
    var iframeBody = document.getElementsByTagName("body")[0];
    var jQuery = function (selector) { return parent.jQuery(selector, iframeBody); };
    var $ = jQuery;
}

Somehow the document object was also undefined.

Source of above code: https://gist.github.com/843229

Hope it helps someone.

like image 38
Manoj Aggarwal Avatar answered Sep 18 '22 17:09

Manoj Aggarwal