In my project, I am dynamically loading content into an iframe
based on the results of a SQL query that is influenced by user input. This requires the height of the iframe
to be adjusted regularly to maintain consistent page layout.
Initially, when the page loads, I use the following code to set the height of the iframe
:
onload="this.height=this.contentWindow.document.body.scrollHeight;"
While this works when the page loads for the first time, it does not work when the user dynamically changes the content of the iframe
. In such cases, the iframe
retains its original height because the onload event is not retriggered.
This is how I include the iframe
in my index.php file when the page is first loaded:
<script>document.write('<iframe id="mainpage-iframe" onload="this.height=this.contentWindow.document.body.scrollHeight;" src="page-body.php"></iframe>');</script>
When the user selects options from a menu to update the content of the iframe
with results from a SQL query, a function like the following is executed:
document.getElementById('mainpage-iframe').contentDocument.location.assign('page-body.php?selectvenue=' + venue + '&selectcity=' + city);
This function essentially passes arguments to the page-body.php.
My question is: is there a way to dynamically add the onload
event to the document.write
function so that the height of the iframe
is adjusted automatically when the content is changed by the user?