kdjernigan
kdjernigan

Reputation: 397

Javascript/Jquery: Auto adjust height of iframe (how to make iframe smaller when needed)

I have the following code that makes the iframe taller once text exceeds iframe visible height; however, when text is removed, the iframe remains just as tall. How do I modify this code (or if there is a different code) that will adjust the iframe to be JUST the right height. I need this to be in a function so that on keyup I can run the function.

function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}

Upvotes: 0

Views: 180

Answers (1)

hemanth
hemanth

Reputation: 1043

Disclaimer: Not sure if below solution is the best one.

You can reset iframe to your standard size and then resize it using your method.

Example:

If the standard size of your iframe is 300px by 300px

function autoResize(id){
   //Reset iframe size
   document.getElementById(id).height= "300px";
   document.getElementById(id).width= "300px";

   //Your method continues
   var newheight;
   var newwidth;

   if(document.getElementById){
       newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
       newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
   }

   document.getElementById(id).height= (newheight) + "px";
   document.getElementById(id).width= (newwidth) + "px";
}

Hope this helps

Upvotes: 1

Related Questions