Tuesday, 8 March 2016

Set iframe height dynamically through Javascript / jQuery

Add an event listener in the parent document (the page where you called iframe)

<script type='text/javascript'>
window.addEventListener('message', function(e) {
    var data = e.data[1];
    var eventName = e.data[0];
    if(eventName=='setHeight') { document.getElementById('iframeID').height = data; }
}, false);
</script>


Write below function into your iframe,

This function will fetch document height and called parent page function to set height dynamic.
<script type='text/javascript'>
function setSize() {
  var height = document.body.scrollHeight;
  window.parent.postMessage(["setHeight", height], "*");
}


Call this function inside iframe through onload event
$( window ).load(function() {
  setSize();
});
    OR
<body onLoad="setSize();">
</script>

No comments:

Post a Comment