Resize iframe based on its content

7

How can I achieve that if the content increases or decreases in size, does the iframe that contains it adjust?

If there is a JQuery plugin, pure JavaScript or a simple solution would be a great contribution since what I can only do is that it adapts to the content once it has finished loading, but not every time it is modified.

I attach the code that I have at the moment:

document.getElemenById('iframeToResize').onload = function() {
  var newheight = this.contentWindow.document.body.scrollHeight,
    newwidth = this.contentWindow.document.body.scrollWidth;

  this.height = (newheight) + 'px';
  this.width = (newwidth) + 'px';
};
<div id="iframeDiv">
  <iframe src="dominio.com/pagina" width="100%" height="100px" id="iframeToResize" marginheight="0" frameborder="0"></iframe>
</div>

Sources of support:

  • How can I detect whether an iframe is loaded? - Stack Overflow
  • Adjust width height of iframe to fit with content in it - Stack Overflow
  • asked by Chofoteddy 05.12.2015 в 13:01
    source

    3 answers

    9

    You can access <iframe> from the content of this (as long as they are from the same domain):

    var iframe = window.parent.document.getElementById('miIframe');
    

    For your particular case, you should have something similar to:

    window.onresize = function() {
        var iframe = window.parent.document.getElementById('miIframe');
        iframe.style.width = window.style.width;
        iframe.style.height = window.style.height;
    }
    

    Take into account the values of margin of the content of the iframe so that the calculation is more precise.

    Try and let me know.

        
    answered by 05.12.2015 в 18:37
    1

    You could use Seamless.js , you find it very useful for IFrames .

    It is excellent to be able to work with dynamic content.

        
    answered by 06.12.2015 в 03:40
    0

    Try the FIT.js library. This library uses the scale of css3 properties to resize a div or any element of dom based on its original position and dimensions to maintain the proper proportions.

    Link to the library link

        
    answered by 31.01.2016 в 00:06