Doua Beri Doua Beri - 2 months ago 9
HTML Question

iframe height for values lower than 150px

I want to change the iframe height based on how the iframe content changes, but I'm having problems if the iframe's content has a height value lower than 150px.

I've tested this code in Firefox and Chrome and it has the same result.
Here you can test it https://jsfiddle.net/bqvc0pp5/17/

From what I've seen if no height is specified the iframe will automatically have 150px(without border).
In this example I increased the value to 300px then lowered to 200px than to 50px . Everything works great until the 50px is converted to 150px;

var iframe = document.createElement('iframe');
iframe.setAttribute("scrolling","no");

iframe.onload = () => {
builtElement();
};

//append iframe to main document
document.body.appendChild(iframe);

var k=0;


function builtElement(){
var div = document.createElement('div');
div.style.height="50px";
div.style.backgroundColor="salmon";
iframe.contentWindow.document.body.style.margin="0px";
iframe.contentWindow.document.body.appendChild(div);

div.addEventListener("click", () =>{
if(k==0){
div.style.height="300px";
}
if(k==1){
div.style.height="200px";
}
if(k==2){
div.style.height="50px";
}
if(k>=2) k=0;
else k++;
updateIframeHeight();
});
}


function updateIframeHeight(){
//I need to reset height or else scrollHeight will be the last max value
iframe.style.height="";
var height = iframe.contentWindow.document.body.scrollHeight;
//this is a dirty hack where I can check if offsetHeight is lower than 150px
var offsetHeight = iframe.contentWindow.document.body.offsetHeight;
//if(offsetHeight<150) height=offsetHeight;
console.log("scrollHeight: "+height);
console.log("scrollHeight: "+offsetHeight);
iframe.style.height=height+"px";
}


If I do a little hack and check if the
offsetHeight
is lower than 150px it works.

var offsetHeight = iframe.contentWindow.document.body.offsetHeight;
if(offsetHeight<150) height=offsetHeight;


Is this the best way to do this?

UPDATE: In a real example, the iframe body contains more than one elements, but only certain elements change height, therefor changing the body scrollHeight

Answer

I found the solution. All you have to do is set the size to 0px;

iframe.style.height="0px";

What I did previously iframe.style.height=""; set the height to 150px by default. It appears that if no size is specified the iframe size will be 150px;