In this JavaScript tutorial you will learn how to program and work with IFRAME elements.

Being an evolution of the old and primitive <frameset> implementation, iframes (or inline frames) permit you to independently embed content from another web page - be it static or dynamic - into the containing or parent HTML document in a very simple fashion.

While it’s fair to admit that during the years, iframes found their place in the toolbox of many web designers (something that effectively contributed to the spread of the boundaries of their existing popularity), the truth is that with the arrival of brand new technologies such as AJAX and the still immature –yet promissory - web workers and web sockets, the shiny halo that once surrounded them has turned into a progressively opaque and vanishing glow.

In addition, there’s another strong reason that made iframes quite unpopular over time: they were wiped out from the XHTML Strict specification; if you’re sticking to “strict” when coding your own web pages, forget about using iframes, because they will make your validator (whichever you currently use) complain loud and clear.

Despite of all these drawbacks, there’s a certain number of use cases where you still might need to work with iframes. For instance, there’re some web services out there that will require you to use these elements for dumping the output that they generate. Or you might deal with legacy code that relies heavily on iframes to work and you don’t want to go through the hassles of refactoring it from top to bottom.

Considering the possibility that you might have to face some of the aforementioned hypothetical situations, in the lines to come I’ll be coding a few examples that will show you how to include iframes in your HTML documents, and how to tweak them a little bit with JavaScript as well.

Creating an introductory example: using an iframe with static content

As explained in the introduction, iframes can be used for inserting content from another HTML document into the current web page, pretty similar to what you can do with framesets. However, if you never had the chance to work with iframes and want to know how to code one, below I created a simple example, which shows how to accomplish this in a nutshell.

In this particular case, the “parent” web page has the following definition:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example using an IFRAME</title>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: normal 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h2 {
    margin: 0 0 10px 0;
    font-size: 2.8em;
    color: #676767; 
}
p {
    margin: 0 0 15px 0;
    line-height: 1.3em;
}
/* main wrapper */
#wrapper {
    width: 780px;
    margin: 0 auto;
    background: #fff;
}
/* header, main and footer elements */
#header, #main, #footer {
    padding: 20px;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h2>Header section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
    <div id="main">
        <iframe src="iframe.htm" width="80%" height="400" scrolling="auto" frameBorder="0">
            <p>Oops! Your browser does not support IFRAMES.</p>
        </iframe>
    </div>
    <div id="footer">
        <h2>Footer section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
</div>
</body>
</html>

As the above code bit shows, including an iframe into an HTML document is indeed a breeze, as the process is reduced to coding the corresponding <iframe> tag along with a few additional attributes, such as “src”, “width”, “height”, “scrolling” and “frameborder”.

Of course, the attributes in question are pretty self explanatory, so pay attention to the value assigned to “src”. As you may have guessed, this one specifies the URL from which content must be embedded into the parent web page. In this case, it turns out to be a static file called “iframe.htm”, whose source code looks like this:

(iframe.htm)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>This is the IFRAME</title>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: normal 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h1 {
    margin: 0 0 10px 0;
    font-size: 2.8em;
    color: #00f; 
}
p {
    margin: 0 0 15px 0;
    line-height: 1.3em;
}
#wrapper {
    width: 400px;
    margin: 10px auto;
}
</style>
</head>
<body>
<div id="wrapper">
    <h1>This is the content of the iframe</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
</div>
</body>
</html>

There’s not much that can be said about this new sample file, as it only defines a few typical sections. Therefore, do something more useful and point your browser to the parent web page. If all goes as expected (and assuming that you already created the corresponding “iframe.htm” file), you should be confronted with an output similar to this one: 

That was really easy to code and read, right? In a jiffy, we managed to create a simple iframe, which dumps the content of a static file into the containing web page. Before you start playing around with the previous example and start adding to it your own tweaks though, take a closer peek at it. Even though there’s nothing wrong with this approach, it uses a transitional DTD.

In short, does this mean that it’s not possible to use iframes with XHTML Strict documents? Well, as I said before, the elements were effectively removed from the standard, yet there’s plenty of room to use them in “strict” pages, even at the expense of implementing some tricky JavaScript hacks.

Given that, in the coming section I’ll be showing you how to include the same iframe that you saw before in an XHTML strict document, but this time the element will be created with plain JavaScript.



Creating and embedding an iframe in a web page with Javascript is a process that doesn’t differ from doing the same with any other HTML element. As explained in the preceding segment, the reason for doing this is to append the iframe to XHTML Strict documents, without making them fail when using a validator.

Of course, this is a quick and dirty approach. Having clarified that, and assuming that you can live happily and without remorse with this issue, take a look at the following code fragment, which builds up the same iframe coded previously, but this time using plain JavaScript: 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example creating an IFRAME with JavaScript</title>
<script type="text/javascript">
// create the IFRAME
function createIframe() {
    var cont = document.getElementById('main');
    if (!cont){return};
    // create the IFRAME element
    var iframe = document.createElement('iframe');
    // assign the attributes to the element
    iframe.setAttribute('src', 'iframe.htm');
    iframe.setAttribute('width', '80%');
    iframe.setAttribute('height', '400px');
    iframe.setAttribute('scrolling', 'auto');
    iframe.setAttribute('frameBorder', 0);
    cont.innerHTML = '';
    // append the IFRAME element to the 'main' container
    cont.appendChild(iframe);
}
// insert the IFRAME element after the web page finishes loading
window.onload = function() {
    createIframe();
}
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: normal 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h2 {
    margin: 0 0 10px 0;
    font-size: 2.8em;
    color: #676767; 
}
p {
    margin: 0 0 15px 0;
    line-height: 1.3em;
}
/* main wrapper */
#wrapper {
    width: 780px;
    margin: 0 auto;
    background: #fff;
}
/* header, main and footer elements */
#header, #main, #footer {
    padding: 20px;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h2>Header section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
    <div id="main">
        <p>To load the IFRAME you must enable JavaScript on your browser...</p>
    </div>
    <div id="footer">
        <h2>Footer section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
</div>
</body>
</html>

From the above snippet, it’s clear to see how easy it is to create and embed an iframe dynamically by means of a few common DOM methods. Since the function that performs this task (which not surprisingly is called “createIframe”) is very simple to grasp, I suggest you move on and check out the following screen capture, which shows the outcome that the earlier web page generates: 

For obvious reasons, the appearance of this dynamically-created iframe is identical to the static one that you saw in the previous section. In this case though, the parent XHTML document has a “Strict” DTD and won’t break up if you test it with your validator. Of course, this is only partially true as the validation will effectively fail if you use the document’s “real” version. But if you want to stick to strict documents and use iframes at the same time, you’ll have to appeal to this kind of dirty solution. You’ve been warned.

So far, so good. At this point, you learned how to build an iframe with raw JavaScript. So, what comes next? With all the hype that currently surrounds it, it’d be a shame not to show how to use jQuery to build an iframe, considering that the library makes this process a no-brainer.

In keeping with this idea, in the lines to come I’ll be setting up a final example which will demonstrate how to generate an iframe using jQuery. If this hasn’t caught your attention yet, you’ll also see how to write some data to the iframe as well.

Creating a Final Example: Building an iframe Dynamically with jQuery   

In reality, creating an iframe with jQuery is so simple that the process itself doesn’t bear any further discussion. The most interesting facet of it, however, is that it’s possible to populate the iframe with dynamic content, instead of using a traditional “src” attribute.

If you’re wondering how can this be accomplished with minor hassles, look at the following code sample, which should make things a bit clearer for you:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example creating an IFRAME with jQuery</title>
<script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    // create the IFRAME element
    var iframe = $('<iframe name="myiframe" width="400" height="400">');
    // append the element to the 'main' container
    $('#main').append(iframe);
    // get the document of the IFRAME
    var iframeDoc = iframe[0].contentWindow.document;
    // write some content to the IFRAME
    iframeDoc.write('<p>This paragraph was added with jQuery!');
    iframeDoc.close();
});
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: normal 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h2 {
    margin: 0 0 10px 0;
    font-size: 2.8em;
    color: #676767; 
}
p {
    margin: 0 0 15px 0;
    line-height: 1.3em;
}
/* main wrapper */
#wrapper {
    width: 780px;
    margin: 0 auto;
    background: #fff;
}
/* header, main and footer elements */
#header, #main, #footer {
    padding: 20px;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h2>Header section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
    <div id="main">
        <h2>Creating an IFRAME with jQuery...</h2>
    </div>
    <div id="footer">
        <h2>Footer section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
    </div>
</div>
</body>
</html>

As this brand new example shows, using jQuery to dump an iframe into a web page is a process that can be mastered in a snap, reduced to creating the corresponding element and then appending it to the DOM. Needless to say that the most relevant aspect of the whole rendering procedure is the bit that writes data to the iframe: to be honest, there’re several ways to do this that will yield satisfactory results; nevertheless, in this case I decided to use the “contentWindow” object, which permits you to access the iframe and print some content to it in a cross-browser fashion. 

What’s more, if you try out the earlier web page using your own browser (yes, you’re fee to utilize Internet Explorer as well), you should see a neatly iframe rendered on screen, similar to the one depicted by the following image:

There you have it. Even when XHTML Strict documents and iframes are mutually exclusive, you can take advantage of the functionality offered by JavaScript (and thereby jQuery) to pretend that they’re compatible. Of course, you always can use a transitional DTD and use iframes without feeling guilty. As usual, it’s up to you to pick the option that best suits your needs.

Final Thoughts

In the course of this article, I provided you with a few approachable examples that hopefully put you on the right track to kick off using iframes on your web pages. As I said before, the elements aren’t that popular as they used to be in the past, as they’ve been progressively deprecated in favor of more efficient and modern approaches. Despite of this, if you still need to appeal to them, the process is everything but complicated.

See you in the next web design tutorial!