Doua Beri Doua Beri - 1 month ago 5x
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

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.onload = () => {

//append iframe to main document

var k=0;

function builtElement(){
var div = document.createElement('div');"50px";"salmon";"0px";

div.addEventListener("click", () =>{
if(k>=2) k=0;
else k++;

function updateIframeHeight(){
//I need to reset height or else scrollHeight will be the last max value"";
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);"px";

If I do a little hack and check if the
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


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

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