Quantcast
Channel: Coding – Infopitcher
Viewing all articles
Browse latest Browse all 11

Make iframe automatically adjust height according to the contents in it using javascript (Support Cross-Domain)

$
0
0

In some pages in your application you may need to feed content form other domain or other pages from same domain using iFrame . We normally set width and height for the iFrame so if the content is bigger than iFrame, scroll will appear automatically. Here is the JavaScript that can fix height dynamically using window.postmessage() method.

Page 1

This document contains iFrame and expect message from another page.

<!doctype html>
<html>
<head>
<title>Page 1/title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
</head>
<body style=”margin:20px;”>
<iframe src=”iframe-content.html” id=”ip_iframe” style=”width:100%;border: solid 1px #ddd” scrolling=”no”></iframe>
<script type=”text/javascript”>
var ip_resize = function (event) {
var ip_iframe = document.getElementById(‘ip_iframe’);
if (ip_iframe) {
ip_iframe.style.height = event.data + “px”;
}
};
if (window.addEventListener) {
window.addEventListener(“message”, ip_resize, false);
} else if (window.attachEvent) {
window.attachEvent(“onmessage”, ip_resize);
}
</script>
</body>
</html>

Page 2

This page will send the message to the above page using java script method window.postmessage() , in our case it will send the height of the page. Here the target origin is set as * since this example is based on same domain if your calling a page from other domain use exact location Eg: “http://yourdomain.com”.

<!doctype html>
<html>
<head>
<title>Page 2</title>
<meta charset=”utf-8″>
<script type=”text/javascript”>
function resize_iframe(){
var body = document.body,
html = document.documentElement,
height = Math.max(body.scrollHeight, body.offsetHeight);
if (parent.postMessage) {
parent.postMessage(height, “*”); /*if calling page from other domain use domain name instead of “*” eg.: “http://yourdomain.com” */
}
}
</script>
</head>
<body onload=”resize_iframe();”>
Content goes here
</body>
</html>

Viewing all articles
Browse latest Browse all 11

Latest Images

Trending Articles





Latest Images