Stevenson C
Stevenson C

Reputation: 15

Auto-scale contents based on width and height of an <iframe>

In TrueBlueAussie's Solution, an iframe becomes proportionally scaled based on the DIVs width and height. Here's his modified version that I prefer: JSFiddle

So my question is, how could I make the contents inside an iframe (after being adjusted using the solution) be automatically and proportionally scaled based off the iframes width and height? When I mean contents, I mean everything inside of it such as images, texts, etc.

After researching, I stumbled upon an attribute that may solve my problem, but after using it with the solution, it had no effect.

Style/CSS Attribute(s):

-ms-zoom: 0.75;
-moz-transform: scale(0.75);
-moz-transform-origin: 0 0;
-o-transform: scale(0.75);
-o-transform-origin: 0 0;
-webkit-transform: scale(0.75);
-webkit-transform-origin: 0 0;

It seems to me that the effect only takes action when the width and height are left alone. I'm trying to achieve the zoom effect used in the attribute so I don't dynamically interfere with the contents inside.

Do I have to use JavaScript to achieve this? I've been stuck on this problem for about a week and can't seem to find a solution.

I do understand the Same-origin policy when it comes to using external sites within the iframe. I'm NOT interested in loading content from external sources.

Upvotes: 0

Views: 2287

Answers (1)

Julien Grégoire
Julien Grégoire

Reputation: 17144

One very simple solution would be to set your measure to percentages. If you can't work this way, I think transform is your best solution. Your resize function already does a part of the calculations, what you need to add is a variable to get the initial width of your iframe, then instead of resizing by setting a new width and height, you use the newWidth variable to set a scale factor and you use it in your tranform css. Like this:

Set the initial width variable just after the iframe is added to the DOM:

    var iframe = document.getElementById('frame'),
    iframedoc = iframe.contentDocument || iframe.contentWindow.document;
    iframedoc.body.innerHTML = source, iframeinitialwidth = $('iframe').width();

On resize, you use newWidth to calculate the scale you should use and you resize with transform (I've made it with -webkit only but it should work on navigator supporting transform):

    ...
    //$iframe.width(newWidth);
    //$iframe.height(newHeight);
    });
    var scaleFactor = newWidth/iframeinitialwidth
    $('iframe').css({'-webkit-transform': 'scale('+scaleFactor+')', '-webkit-transform-origin': '0 0'})
   ...

http://jsfiddle.net/368sjapg/2/

Upvotes: 1

Related Questions