0

I have a dynamically created iframe made with regular javascript. It works great when its called from a static page by regular means, but when called from a page loaded by Jquery, I get a 'myIframe is null' error.

var link = 'http://www.blah.com'
var iframe='<iframe class="adframe" id="randomnumberhere" name="widget" src="#" width="300" height="250" marginheight="0" marginwidth="0" frameborder="no" scrolling="no"></iframe>';

document.write(iframe);
var myIframe=parent.document.getElementById("randomnumberhere");
myIframe.height=250;
myIframe.width=300;
myIframe.src=link;
myIframe.style.border="0px";
myIframe.style.padding="0px";
3
  • Do you have this thing loaded in a $(function() tag, or what? You simply added the jQuery library and this doesn't work anymore? Commented May 27, 2012 at 5:01
  • No. It's not in any function. That's the code. I just stuck it into a page that's called by JQuery. I use the code for ad placement. It'll create an iFrame wherever I place it. Commented May 27, 2012 at 5:11
  • question: you are calling var myIframe=parent.document.getElementById("randomnumberhere"); but look like you are not in a child so should be var myIframe=document.getElementById("randomnumberhere"); ? Commented May 27, 2012 at 6:51

1 Answer 1

1

I solved this one by adding a div with a unique id then append the iFrame to that div. It seems document.write can make the object, but appending to that element wasn't happening. The working code is below.

Have a dynamically created random number for the div in the html already there:

<div id="randomid"></div>

Then I made a function to append to that div with that specific id

function makeFrame(){
var link = 'http://blah.com'
ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", link);
ifrm.style.width="300px";
ifrm.style.height="250px";
ifrm.style.border="0px";
ifrm.style.padding="0px";
document.getElementById('randomid').appendChild(ifrm);
}
makeFrame();

This will only work if the div is already on the page. I couldn't figure out a way to dynamically make the div and then append the iFrame to that div. Document.write made the div, but it couldn't append the iFrame to that element. Perhaps a delay would make it work? Below is what I tried, but didn't work.

var iDiv='<div id="randomid"></div>';
document.write(iDiv);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.