Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically resize iframe

Situation: I'm working on a responsive design that involves the typical HTML/CSS combo. Everything is working nicely except in one case where there is an iframe inside of a div. The iframe should adjust automatically to the size of the parent div. A purely css solution has not presented itself so I'm going with a JQuery approach. It works nicely except in one scenario, when resizing from a smaller width to a larger width screen.

HTML:

<div class="container">
    <iframe class="iframe-class" src="http://www.cnn.com/"></iframe>
</div>

CSS:

.container {
    width: 100%;
    height: 250px;
}
.iframe-class {
    width: 100%;
    height: 100%;
    border: 1px solid red;
    overflow: auto;
}

Javascript:

$(function () {
    setIFrameSize();
    $(window).resize(function () {
        setIFrameSize();
    });
});

function setIFrameSize() {
    var ogWidth = 700;
    var ogHeight = 600;
    var ogRatio = ogWidth / ogHeight;

    var windowWidth = $(window).width();
    if (windowWidth < 480) {
        var parentDivWidth = $(".iframe-class").parent().width();
        var newHeight = (parentDivWidth / ogRatio);
        $(".iframe-class").addClass("iframe-class-resize");
        $(".iframe-class-resize").css("width", parentDivWidth);
        $(".iframe-class-resize").css("height", newHeight);
    } else {
        // $(".iframe-class-resize").removeAttr("width");
        // $(".iframe-class-resize").removeAttr("height");
        $(".iframe-class").removeClass("iframe-class-resize");
    }
}

http://jsfiddle.net/TBJ83/

Problem: As the window is resized smaller, it continually checks the window width and once it hits < 480 px, the code adds a class called iframe-class-resize and sets the width and height to that class. As the window is resized larger, it removes the class once the size hits 480 px. The problem is that setting the width and height attributes adds them directly to the element and not the class itself. Therefore, removing the class does not remove the new width and heights. I tried to force removing the attributes using removeAttr() (commented out above) but that didn't work.

Anyone see where the code above went wrong? Or any suggestions on how to accomplish having a responsive iframe more effectively? The main things that are required are that the iframe has to be inside the <div></div> and the div may not necessarily have a width or height defined. Ideally, the parent div should have the width and height explicitly defined but the way this site is currently setup, that won't always be possible.

Additional: In case the above wasn't clear enough, try the following to reproduce the issue:

  • Open up a browser on a desktop machine. I'm using Chrome on a Windows machine. Don't maximize the browser.
  • Open up the jsfiddle above (http://jsfiddle.net/TBJ83/). You'll notice that the iframe content spans the entire width of the Preview panel.
  • Manually resize the width down until the entire window is < 480px. At this point, the iframe content will be pretty tiny.
  • Manually resize the width back up until the entire window is >> 480px. The goal is to have that iframe content to regain the entire width of the Preview panel. Instead, the content is retaining the resized width and height since the .css() function applies css changes directly to elements rather than to the classes.

Thanks in advance!

like image 747
jiminy Avatar asked Feb 19 '14 00:02

jiminy


People also ask

How do I automatically resize an iframe?

You can use the JavaScript contentWindow property to make an iFrame automatically adjust its height according to the contents inside it, so that no vertical scrollbar will appear.

How do I resize an iframe in HTML?

Edit the width attribute. You should see the attribute "width=" after the URL in the iframe tag. Edit the width in pixels in quotations (" ") after the "width=" attribute. For example, if you want the width to be 300 pixels, you would enter "width="300px"" after the URL in the tag.


2 Answers

You can do this in about 30 characters. Change:

$(".iframe-class").removeClass("iframe-class-resize")

to:

$(".iframe-class").removeClass("iframe-class-resize").css({ width : '', height : '' })

This will reset the width/height you applied to the element. When you use .css() you add whatever you pass-in to the style attribute of the element. When you pass a blank value, jQuery removes that property from the style attribute of the element.

Here is an updated fiddle: http://jsfiddle.net/TBJ83/3/

EDIT

OK, here's something tweaked for performance (and just some other ways to do things):

$(function () {

    //setup these vars only once since they are static
    var $myIFRAME   = $(".iframe-class"),//unless this collection of elements changes over time, you only need to select them once
        ogWidth     = 700,
        ogHeight    = 600,
        ogRatio     = ogWidth / ogHeight,
        windowWidth = 0,//store windowWidth here, this is just a different way to store this data
        resizeTimer = null;

    function setIFrameSize() {
        if (windowWidth < 480) {

            var parentDivWidth = $myIFRAME.parent().width(),//be aware this will still only get the height of the first element in this set of elements, you'll have to loop over them if you want to support more than one iframe on a page
                newHeight      = (parentDivWidth / ogRatio);

            $myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
        } else {
            $myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
        }
    }

    $(window).resize(function () {

        //only run this once per resize event, if a user drags the window to a different size, this will wait until they finish, then run the resize function
        //this way you don't blow up someone's browser with your resize function running hundreds of times a second
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
            //make sure to update windowWidth before calling resize function
            windowWidth = $(window).width();

            setIFrameSize();

        }, 75);

    }).trigger("click");//run this once initially, just a different way to initialize
});
like image 88
Jasper Avatar answered Sep 20 '22 16:09

Jasper


This can be done using pure CSS as below:

iframe {
  height: 300px;
  width: 300px;
  resize: both;
  overflow: auto;
}

Set the height and width to the minimum size you want, it only seems to grow, not shrink.

like image 33
Abhi Andhariya Avatar answered Sep 18 '22 16:09

Abhi Andhariya