4

Introduction
Lets say you have a website with a mobile version and a desktop version. Pictures can be resized proportinally using css on either version. But not all html tags resize proportionally, for instance: iframes.

Javascript Function
includes: the id of the iframe, the original width and original height

See code below.

the iframe

<iframe id="iemovie" onload="resizeiframecent('iemovie','800','450')" src="http://www.youtube.com/embed/J-HieaOI00s?html5=1" width="100%" > </iframe>
  • notice the height is absent but the width is 100%. it will adjust to the parent element's width; usually a div with its preset width, say 800px for desktop, and 90% for mobile.
  • notice the onload attribute
  • when iframe loads the function takes the original proportions oldx and oldy and compares them to the actualwidth
  • the math.ceil funtion rounds up the newheight and creates a new variable called newheight2
    then, the iframe gets a newly defined height atribute based proportionally based on the original height
  • do not set the iframe proportions via css or else you will have to change the code from document.getElementById(ifid).height=newheight2; to document.getElementById(ifid).style.height=newheight2;

Edited by pritaeas: Changed to code snippet.

Votes + Comments
This is exactly what I needed. Thank you for your wonderful work
Nice!
function resizeiframecent(ifid, oldx, oldy) {
     
    var actualwidth = document.getElementById(ifid).offsetWidth;
     
    var proporcion = actualwidth / oldx;
    newheight=proporcion * oldy;
    var newheight2 = Math.ceil(newheight);
     
    document.getElementById(ifid).height = newheight2;
     
}
4
Contributors
7
Replies
54
Views
4 Years
Discussion Span
Last Post by Hicaro_1
0

Lets say you have a website with a mobile version and a desktop version.

Is this a tutorial?

If so, let a Moderator know so he will change this thread into a tutorial/code snippet thread

0

It's a nice code snippet.

I didn't know you can change the size on a iFrame by using javascript like that.

Thanks for sharing.

Edited by LastMitch: grammer

0

Well in theory any element of html could be resized with it. The key is line 3 of the javascript where the actual size of the element is measured. Everything depends on having the offsetWidth give you a width.

0

Yeah, chrome (win and ios), IE9 and 10 and safari (win iphone and ipad)

0

Excelente Rodrigo

onload="resizeiframecent(this,'1920','496')"

function resizeiframecent(ifid, oldx, oldy) {
    var actualwidth = ifid.offsetWidth;
    var proporcion = actualwidth / oldx;
    newheight=proporcion * oldy;
    var newheight2 = Math.ceil(newheight);
    ifid.height = newheight2;
}

Edited by pritaeas: This is an English ONLY forum.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.