How can I change the size of an iframe from inside?
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');
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>