iStore Info

This Blog to Store All Information Related to Oracle EBS Apps, Useful Applications, Latest Technology.

How to adjust the width and height of iframe to fit with content in it ?

 Using iframe tag the content inside the tag is displayed with a default size if the height and width are not specified. thou the height and width are specified then also the content of the iframe tag is not displayed in the same size of the main content. It is difficult to set the size of the content in the iframe tag as same as the main content. So its need to be dynamically set the content size when the content of iframe is loaded on the web page. Because its not possible to set the height and width all the time while the same code execute with a different content.

There is a way to make it dynamically by using some attribute of JavaScript.
The attributes used here are,

  • contentWindow : This property returns the Window object used by an iframe element, basically its defines the iframe window.
  • scrollHeight : This property defines the entire height of an element in pixels, the element is iframe.
  • scrollWidth : This property defines the entire width of an element in pixels, the element is iframe.

Example:

<!DOCTYPE html>
<html>
<head>
<h4 style="color:#006400; font-size:24px;">
Adjust width and height of iframe to fit 
with content in it using JavaScript</h4>
</head>
<body>
    <iframe style="width: 100%;border:3px solid black; 
     " src="iframe Pge.html" id="Iframe"></iframe>
    <!--iframe tag-->
      
    <script>
        // Selecting the iframe element
        var frame = document.getElementById("Iframe");
          
        // Adjusting the iframe height onload event
        frame.onload = function()
        // function execute while load the iframe
        {
          // set the height of the iframe as 
          // the height of the iframe content
          frame.style.height = 
          frame.contentWindow.document.body.scrollHeight + 'px';
           
  
         // set the width of the iframe as the 
         // width of the iframe content
         frame.style.width  = 
          frame.contentWindow.document.body.scrollWidth+'px';
              
        }
        </script>
</body>
</html>