How to change height of iframe when it loads?

by scotty_walker , in category: Javascript , 2 months ago

How to change height of iframe when it loads?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 2 months ago

@scotty_walker 

You can change the height of an iframe when it loads using JavaScript. You can set the height of the iframe based on its content using the contentWindow property of the iframe element. Here's an example code snippet to change the height of an iframe when it loads:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<title>Change iframe height on load</title>
<script>
window.onload = function() {
  var iframe = document.getElementById('myIframe');
  var iframeHeight = iframe.contentWindow.document.body.scrollHeight + 'px';
  iframe.style.height = iframeHeight;
};
</script>
</head>
<body>
<iframe id="myIframe" src="http://example.com" width="100%" scrolling="no"></iframe>
</body>
</html>


In this code snippet, the height of the iframe is set based on the scrollHeight of the body of the content inside the iframe. This way, the height of the iframe will adjust dynamically based on the content it loads. You can adjust the height calculation based on your specific requirements.