skip to Main Content

I’m trying to get an iframe into loading at its full height.

I am working from within the confines of WordPress Elementor, but I don’t think that’s holding me back.

I have a section on a page

<iframe id='iframe1' src="https://example.com/my.html" style="display:none" title="iframe1"></iframe>

So the iframe is in the DOM with display initially set to none.

When the user clicks a button on the page, a function does two things

  1. it sets
    theIFrameTag.style.display="inline-block";

  2. theIFrameTag.addEventListener('load', syncHeight); where the function syncHeight is

function syncHeight() {
        this.style.height = `${this.contentWindow.document.body.scrollHeight}px`   
    }

It seems that this.contentWindow.document.body.scrollHeight is initially set to 150 when display is none and so when my function runs, it’s that height not the actual height.

Is there a way to get it to display real height (to display the whole thing and avoid the need for a scroll bar)? Obviously, something has to know the actual height since its displaying that in the 150 pixel high window with a scroll bar.

2

Answers


  1. Chosen as BEST ANSWER

    So it seems that when an iframe is already part of the DOM displayed or not, it's "loaded" and it doesn't load again by changing the display attribute. So the function assigned to listen on load events never gets called. The solution at least as far as drawing the iframe at the right size is to use the MutationObserver to observe for changes to the display attribute. First in the button function do the following

    var observer = new MutationObserver(observeIFrameChange);
                    observer.observe(theIFrameTag,  { attributes: true, childList: false, attributeOldValue: true });
    

    The observeIFrameChange function is as follows

     function observeIFrameChange(mutations){
            for (let mutation of mutations) {
                 if (mutation.oldValue = "display:none") {
                     mutation.target.style.height = `${mutation.target.contentWindow.document.body.scrollHeight}px`;
    
                    
                
                 }
    
            }
          }
    

  2. Just change

    this.style.height = `${this.contentWindow.document.body.scrollHeight}px`
    

    To

    this.style.height = `100vh`   
    

    for more info your can look here https://www.w3schools.com/cssref/css_units.asp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search