Saturday, February 13, 2010

Dynamically create iframe with jQuery

This article explains and shows how to dynamically create an iframe in your HTML document’s DOM using jQuery and/or JavaScript. It also gives you an example code. This post is not extensive explanation of how to manage and work with iframes using jQuery. This post simply shows you how to dynamically create iframes using jQuery and JavaScript and serves as a note.

Creating iframe is similar to creating any DOM element. All you need to do is to use jQuery factory like this:

// Create an iframe element
$(‘<iframe />’);

// You can also create it with attributes set
$('<iframe id="myFrame" name="myFrame">');

// Finnaly attach it into the DOM
$('<iframe id="myFrame" name="myFrame">').appendTo('body');

Don’t forget that the iframe source is just an iframe’s attribute. So you can set that just like any other attribute.

// Setting iframe's source
$('<iframe />').attr('src', 'http://www.google.com'); 

UPDATE:

As BinaryKitten point’s out below, with jQuery 1.4 you can do it using the following syntax:

// Set attributes as a second parameter
$('<iframe />', {
    name: 'myFrame',
    id:   'myFrame',
    ...
}).appendTo('body');

11 comments:

  1. saw this on a tweet, just wondering what would be a purpose of doing this?

    ReplyDelete
  2. in 1.4 and above you can use the new style element creation like so $('<iframe />', {"name":"googleFrame","id":"googleFrame","src":"http://www.google.com"}).appendTo('body');

    ReplyDelete
  3. this really required a post? this is essentially a copy/paste from the jquery docs.

    ReplyDelete
  4. I was expecting similar comments. As I already wrote in the post itself, it is just a note and nothing special. It serves for those who actually need it (ex: jQuery newbee). And according to the GA there are several of those already...

    ReplyDelete
  5. I found this post useful. I am a JQuery newbee and it helped me out. Keep up the great posts!

    ReplyDelete
  6. I too wanted a quick answer and this post helped me.

    ReplyDelete
  7. Yeah it helped me out too, cheers Uzbekjon! :)

    ReplyDelete
  8. You can use this to load youtube videos on your page just like FB.

    ReplyDelete
  9. you could have just pointed to the jquery documentation instead of copy/paste content from it

    ReplyDelete