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;
var newheight2 =  Math.ceil(newheight);

the iframe

<iframe id="iemovie" onload="resizeiframecent('iemovie','800','450')" src="" 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

Location #1510 Juan Ponce de León Ave. Suite 6B,
San Juan, PR 00923.

icon 2 787-313-6606

icon 3

Security Text: Copy the letters in the image