How to Dynamically Resize an iFrame

We've already talked about how, as developers, iFrames can sometimes be our worst enemies. Because their content is often hosted on another server (as well as their stylesheets), they can be a huge pain to change around and manipulate. In our previous iFrame post, we gave you a snippet that can be used to access and change the styling of elements within an iFrame using jQuery, and in this post, we're going to provide a snippet that can be used to dynamically resize an iFrame.

Often, an iFrame's size is determined using inline HTML, which means it can sometimes be hard to override in your stylesheets without performing some CSS trickery (an !important usually works, but this is hardly considered a CSS best practice). A standard iFrame tag might look like this:

<iframe src="URL" width="200" height "300"></iframe>

As you can see, the height and width for this iFrame is predefined in the HTML. So what if you want to change the height and width dynamically based on the size of your iFrame content, rather than by arbitrary pixel definitions? Luckily, there's a snippet for that. Check it out below:

$(function() {
    var iFrames = $('iframe');

    function resize() {
        for (var i = 0, j = iFrames.length; i & lt; j; i++) {
            var nHeight = iFrames[i].contentWindow.document.body.offsetHeight;
            iFrames[i].style.height = nHeight + 'px';
        }
    }
    if ($.browser.safari || $.browser.opera) {
        iFrames.load(function() {
            setTimeout(resize, 0);
        });
        for (var i = 0, j = iFrames.length; i & lt; j; i++) {
            var iSource = iFrames[i].src;
            iFrames[i].src = '';
            iFrames[i].src = iSource;
        }

    } else {
        iFrames.load(function() {
            this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
        });
    }
});

The snippet above creates a function called resize that can be used to dynamically change the height and length of an iFrame based on the size of the content it contains. It will work even if you don't have a predefined width and height of your iFrame in the HTML, however it won't work unless the content within the iFrame comes from the same domain as the page that the iFrame appears on. Give it a try and see if you like how it manipulates the iFrames on your sites!



Responsive Menu
Add more content here...