E
E
exitialis2015-09-30 21:23:53
PHP
exitialis, 2015-09-30 21:23:53

How to change iframe height dynamically?

Greetings, dear users of habr! There was such problem: there is an iframe on the page. Another web application is loaded into this iframe, which dynamically updates the contents of the iframe using ajax. And the question arose, how can I change the height of the iframe depending on the content that is inside it? This used to work:

function resizeIframe(obj){
        obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
    }

But this only works externally and only fires when the page is refreshed. And after I entered ajax, the iframe stopped stretching completely and this happens because the iframe is loaded first, and only then requests occur. Maybe there is some kind of event or is there another way to implement changing the height of the frame? Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2015-09-30
@exitialis

var d = document;

d.addEventListener('DOMContentLoaded', function(){

  var frame = d.getElementById('ifr'), // ваш iframe
  MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
  observer = new MutationObserver(function (mutations) {
    resizeIframe(frame);
    }),
  config = {
    attributes: true,
    childList: true,
    characterData: true,
    subtree: true
  };
  frame.addEventListener('load', function(){
    observer.observe(this.contentDocument.body, config);
    resizeIframe(this);	
  }, false);
  
}, false);

  
function resizeIframe(o){
  o.style.height = o.contentDocument.body.scrollHeight + 'px';	
}
Just keep in mind that MutationObserver is not supported in donkeys below version 11.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question