Skip to content Skip to sidebar Skip to footer

How Can I Change The Size Of An Iframe From Inside?

I am developing with jquery and I stumbled with the next problem: I added an IFrame inside the main page and I want to re size them from inside. I tried some ideas but without succ

Solution 1:

When you create an IFRAME the browser automatically adds a 'window' object for the IFRAME inside the 'window' object of main page.

You need to change the size of the IFRAME instead of the size of the document.

Try this code:

For JavaScript:

window.parent.document.getElementById('myframe').width = '500px';
window.parent.document.getElementById('myframe').height = '500px';

And for jQuery:

$('#myframe', window.parent.document).width('500px');
$('#myframe', window.parent.document).height('500px');

Solution 2:

If both pages are on the same domain (or even subdomain if you set document.domain maybe, did not test it) you can simply set it from javascript (or jQuery):

window.parent.document.getElementById('myframe').width = '500px';

If you the pages are on different domains one solution would be to to add an event listener in the page that is calling the iFrame (credits to Marty Mulligan):

<html>
<head>
    <title>Index</title>
	<script src="/js/jquery/js/jquery.1.10.2.min.js"></script>
	<script>
		window.addEventListener('message', function(e) {
			debugger;
		  var iframe = $("#myIframe");
		  var eventName = e.data[0];
		  var data = e.data[1];
		  switch(eventName) {
			case 'setHeight':
			  iframe.height(data);
			  break;
		  }
		}, false);
	</script>
</head>
<body>
    <iframe id="myIframe" src="http://hofvanzeeland.net/frame.html" width="100px" height="100px" border="1"></frame>
</body>
</html>

and trigger it from the iFrame content (frame.html):

<html>
    <head>
        <title>IFrame</title>		
        <script>            
			function resize() {
			  var height = document.getElementsByTagName("html")[0].scrollHeight;
			  window.parent.postMessage(["setHeight", height], "*"); 
			}
        </script>
    </head>
    <body>
        <h2>My IFrame</h2>
		<a href="#" onclick="resize()">Click me</a>
    </body>
</html>

Solution 3:

function setHeight() {
    parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}

Another way using Javascript

document.getElementById("ifr").height= "500px";
document.getElementById("ifr").width= "500px";

DEMO JSFIDDLE


Post a Comment for "How Can I Change The Size Of An Iframe From Inside?"