Saturday, May 8, 2010

dynamically create iframes using jQuery

jquery-logo

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');


People who read this post also read :



If you liked my post then,

Subscribe to this site via Email:

Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!

DropJack!
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "dynamically create iframes using jQuery"

Post a Comment