CODE: Automatically and proportionally change iframe height for mobile and desktop

Javascript Function

includes: the id of the iframe, the original width and original height
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;
 
}

the iframe

<iframe id="iemovie" onload="resizeiframecent('iemovie','800','450')" src="http://www.youtube.com/embed/J-HieaOI00s?html5=1" width="100%" ></iframe>
  • the iframe tag was broken to avoid rendering
  • 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;

Contact Us

#1510 Juan Ponce de León Ave. Suite 5A1,
San Juan, PR 00923.
Google Maps

+1 (787) 313-6606

info@unlimitedstudios

Security Text: Copy the letters in the image