Creating an iframe with JavaScript

24 February 2009| One Comment| Print

I want to start this post by saying that I’m not a fan of using iframes, however, sometimes due to restrictions within some development environments it may be the only way to embed content into your site of blog.

So whats the point i hear you cry. This code is really only useful if your distributing and sharing widgets from your site. So say you have your own social network and you want to open up the data allow users to embed portions of your site on theirs, this code basically writes a standard iframe on the page using JavaScript, and instead of the user having to copy the whole iframe code (which can be long if you have inline-styles, and long source urls) all you need to include in your page to invoke the widget is the code below.

<!-- one line of JavaScript is all that is needed to generate the iframe. -->
<script language="JavaScript" src="/demos/javascript-iframe/javascript-iframe.js"></script>

And within the javascript file is the following code.

// Set path to the iframe file
var filePath = 'http://www.myspace.com';
// Setup the iframe target
var iframe='<iframe id="frame" name="widget" src ="#" width="100%" height="1" marginheight="0" marginwidth="0" frameborder="no" scrolling="no"></iframe>';
// Write the iframe to the page
document.write(iframe);

var myIframe = parent.document.getElementById("frame");
// Setup the width and height
myIframe.height = 350;
myIframe.width = 960;

myIframe.src = filePath;
// set the style of the iframe
myIframe.style.border = "1px solid #999";
myIframe.style.padding = "8px";

And that’s it, any questions or comments leave them below.

demodownload


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

One Comment

  • John

    The demo goes to myspace website!!§

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here