Home > Enterprise >  Set Height Css Class After Page Load in JavaScript
Set Height Css Class After Page Load in JavaScript

Time:09-17

I need to set the mainContainer class height to the iframe height on page load. Right now its setting the height BUT its cut. Maybe this code is wrong? const iframeHeight = document.getElementById('productIFrame')[0].contentWindow.document.body.offsetHeight 'px';

<div >
    <iframe id="productIFrame" src="https://sample.com" title="" width="100%" height="100%" style="border: none"></iframe>
</div>

<style>
    .mainContainer {
        width: 100%;
    }
</style>

<script type="text/javascript">
    const iframeHeight = document.getElementById('productIFrame').contentWindow.document.body.offsetHeight   'px';
  document.getElementsByClassName("mainContainer")[0].style.height = iframeHeight;
</script>

CodePudding user response:

QUESTION SOLVED!

Solution would be to add postMessage function in the iframe level. and on the main page, you need to add an event listener and extract the height coming from that and assign it to the mainContainer class.

CodePudding user response:

You should be able to use the document.readyState method, and fire your logic once page has loaded.

Something like the below may fix it for you.

<script type="text/javascript">
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
        const iframeHeight = document.getElementById('productIFrame').contentWindow.document.body.offsetHeight   'px';
        document.getElementsByClassName("mainContainer").style.height = iframeHeight;
    }
}

CodePudding user response:

Try to run on local

window.addEventListener('load', (event) => {
        const iFrame = document.getElementById('productIFrame');
        iFrame.contentWindow.document.body.style.margin = "0 0 0 0";
        const iframeHeight = iFrame.contentWindow.document.body.scrollHeight   'px';
        document.getElementsByClassName("mainContainer")[0].style.height = iframeHeight;
    });
html, body {
  margin: 0 !important;
}

.mainContainer {
  width: 100%;
}
<div >
 <iframe frameborder="0" border="0" cellspacing="0"
        style="border-style: none; margin: 0;" id="productIFrame"  title="" width="100%" height="100%" style="border: none"></iframe>
</div>

  • Related