I need a solution for auto-adjusting the width and height of an iframe to barely fit its content. The point is that the width and height can be changed after the iframe has been loaded. I guess I need an event action to deal with the change in dimensions of the body contained in the iframe.
<script type="application/javascript">
function resizeIFrameToFitContent( iFrame ) {
iFrame.width = iFrame.contentWindow.document.body.scrollWidth;
iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}
window.addEventListener('DOMContentLoaded', function(e) {
var iFrame = document.getElementById( 'iFrame1' );
resizeIFrameToFitContent( iFrame );
// or, to resize all iframes:
var iframes = document.querySelectorAll("iframe");
for( var i = 0; i < iframes.length; i++) {
resizeIFrameToFitContent( iframes[i] );
}
} );
</script>
<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>
one-liner solution for embeds:
starts with a min-size and increases to content size. no need for script tags.
<iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
Cross-browser jQuery plug-in.
Cross-bowser, cross domain library that uses mutationObserver to keep iFrame sized to the content and postMessage to communicate between iFrame and host page. Works with or without jQuery.
All solutions given thus far only account for a once off resize. You mention you want to be able to resize the iFrame after the contents are modified. In order to do this, you need to execute a function inside the iFrame (once the contents are changed, you need to fire an event to say that the contents have changed).
I was stuck with this for a while, as code inside the iFrame seemed limited to the DOM inside the iFrame (and couldn't edit the iFrame), and code executed outside the iFrame was stuck with the DOM outside the iFrame (and couldn't pick up an event coming from inside the iFrame).
The solution came from discovering (via assistance from a colleague) that jQuery can be told what DOM to use. In this case, the DOM of the parent window.
As such, code such as this does what you need (when run inside the iFrame) :
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#IDofControlFiringResizeEvent").click(function () {
var frame = $('#IDofiframeInMainWindow', window.parent.document);
var height = jQuery("#IDofContainerInsideiFrame").height();
frame.height(height + 15);
});
});
</script>
If the iframe content is from the same domain this should work great. It does require jQuery though.
$('#iframe_id').load(function () {
$(this).height($(this).contents().height());
$(this).width($(this).contents().width());
});
To have it resize dynamically you could do this:
<script language="javaScript">
<!--
function autoResize(){
$('#themeframe').height($('#themeframe').contents().height());
}
//-->
</script>
<iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>
Then on the page that the iframe loads add this:
<script language="javaScript">
function resize()
{
window.parent.autoResize();
}
$(window).on('resize', resize);
</script>
Here is a cross-browser solution if you don't want to use jQuery:
/**
* Resizes the given iFrame width so it fits its content
* #param e The iframe to resize
*/
function resizeIframeWidth(e){
// Set width of iframe according to its content
if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
e.width = e.contentWindow.document.body.scrollWidth;
else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
e.width = e.contentDocument.body.scrollWidth + 35;
else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
e.width = e.contentDocument.body.offsetWidth + 35;
}
After I have tried everything on the earth, this really works for me.
index.html
<style type="text/css">
html, body{
width:100%;
height:100%;
overflow:hidden;
margin:0px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
$(iframe).height($(iframe).contents().find('html').height());
}
</script>
<iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>
I am using this code to autoadjust height of all iframes (with class autoHeight) when they loads on page. Tested and it works in IE, FF, Chrome, Safari and Opera.
function doIframe() {
var $iframes = $("iframe.autoHeight");
$iframes.each(function() {
var iframe = this;
$(iframe).load(function() {
setHeight(iframe);
});
});
}
function setHeight(e) {
e.height = e.contentWindow.document.body.scrollHeight + 35;
}
$(window).load(function() {
doIframe();
});
This is a solid proof solution
function resizer(id)
{
var doc=document.getElementById(id).contentWindow.document;
var body_ = doc.body, html_ = doc.documentElement;
var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
var width = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );
document.getElementById(id).style.height=height;
document.getElementById(id).style.width=width;
}
the html
<IFRAME SRC="blah.php" id="iframe1" onLoad="resizer('iframe1');"></iframe>
Context
I had to do this myself in a context of a web-extension. This web-extension injects some piece of UI into each page, and this UI lives inside an iframe. The content inside the iframe is dynamic, so I had to readjust the width and height of the iframe itself.
I use React but the concept applies to every library.
My solution (this assumes that you control both the page and the iframe)
Inside the iframe I changed body styles to have really big dimensions. This will allow the elements inside to lay out using all the necessary space. Making width and height 100% didn't work for me (I guess because the iframe has a default width = 300px and height = 150px)
/* something like this */
body {
width: 99999px;
height: 99999px;
}
Then I injected all the iframe UI inside a div and gave it some styles
#ui-root {
display: 'inline-block';
}
After rendering my app inside this #ui-root (in React I do this inside componentDidMount) I compute the dimensions of this div and sync them to the parent page using window.postMessage:
let elRect = el.getBoundingClientRect()
window.parent.postMessage({
type: 'resize-iframe',
payload: {
width: elRect.width,
height: elRect.height
}
}, '*')
In the parent frame I do something like this:
window.addEventListener('message', (ev) => {
if(ev.data.type && ev.data.type === 'resize-iframe') {
iframe.style.width = ev.data.payload.width + 'px'
iframe.style.height = ev.data.payload.height + 'px'
}
}, false)
I slightly modified Garnaph's great solution above. It seemed like his solution modified the iframe size based upon the size right before the event. For my situation (email submission via an iframe) I needed the iframe height to change right after submission. For example show validation errors or "thank you" message after submission.
I just eliminated the nested click() function and put it into my iframe html:
<script type="text/javascript">
jQuery(document).ready(function () {
var frame = $('#IDofiframeInMainWindow', window.parent.document);
var height = jQuery("#IDofContainerInsideiFrame").height();
frame.height(height + 15);
});
</script>
Worked for me, but not sure about cross browser functionality.
all can not work using above methods.
javascript:
function resizer(id) {
var doc = document.getElementById(id).contentWindow.document;
var body_ = doc.body, html_ = doc.documentElement;
var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight);
var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth);
document.getElementById(id).style.height = height;
document.getElementById(id).style.width = width;
}
html:
<div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv" >
<input id="txtHeight"/>height <input id="txtWidth"/>width
<iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0" ></iframe>
<iframe src="left.aspx" name="leftFrame" scrolling="yes" id="Iframe1" title="leftFrame" onload="resizer('Iframe1');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe>
<iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; " onload="resizer('Iframe2');" ></iframe>
</div>
Env: IE 10, Windows 7 x64
I figured out another solution after some experimenting. I originally tried the code marked as 'best answer' to this question and it didn't work. My guess is because my iframe in my program at the time was dynamically generated. Here is the code I used (it worked for me):
Javascript inside the iframe that is being loaded:
window.onload = function()
{
parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
};
It is necessary to add 4 or more pixels to the height to remove scroll bars (some weird bug/effect of iframes). The width is even stranger, you are safe to add 18px to the width of the body. Also make sure that you have the css for the iframe body applied (below).
html, body {
margin:0;
padding:0;
display:table;
}
iframe {
border:0;
padding:0;
margin:0;
}
Here is the html for the iframe:
<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>
Here is all the code within my iframe:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>File Upload</title>
<style type="text/css">
html, body {
margin:0;
padding:0;
display:table;
}
</style>
<script type="text/javascript">
window.onload = function()
{
parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
};
</script>
</head>
<body>
This is a test.<br>
testing
</body>
</html>
I have done testing in chrome and a little in firefox (in windows xp). I still have more testing to do, so please tell me how this works for you.
If you can control both IFRAME content and parent window then you need the iFrame Resizer.
This library enables the automatic resizing of the height and width of both same and cross domain iFrames to fit their contained content. It provides a range of features to address the most common issues with using iFrames, these include:
Height and width resizing of the iFrame to content size.
Works with multiple and nested iFrames.
Domain authentication for cross domain iFrames.
Provides a range of page size calculation methods to support complex CSS layouts.
Detects changes to the DOM that can cause the page to resize using MutationObserver.
Detects events that can cause the page to resize (Window Resize, CSS Animation and Transition, Orientation Change and Mouse events).
Simplified messaging between iFrame and host page via postMessage.
Fixes in page links in iFrame and supports links between the iFrame and parent page.
Provides custom sizing and scrolling methods.
Exposes parent position and viewport size to the iFrame.
Works with ViewerJS to support PDF and ODF documents.
Fallback support down to IE8.
If you can live with a fixed aspect ratio and you would like a responsive iframe, this code will be useful to you. It's just CSS rules.
.iframe-container {
overflow: hidden;
/* Calculated from the aspect ration of the content (in case of 16:9 it is 9/16=
0.5625) */
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
The iframe must have a div as container.
<div class="iframe-container">
<iframe src="http://example.org"></iframe>
</div>
The source code is based on this site and Ben Marshall has a good explanation.
I have been reading a lot of the answers here but nearly everyone gave some sort of cross-origin frame block.
Example error:
Uncaught DOMException: Blocked a frame with origin "null" from
accessing a cross-origin frame.
The same for the answers in a related thread:
Make iframe automatically adjust height according to the contents without using scrollbar?
I do not want to use a third party library like iFrame Resizer or similar library either.
The answer from #bboydflo is close but I'm missing a complete example. https://stackoverflow.com/a/52204841/3850405
I'm using width="100%" for the iframe but the code can be modified to work with width as well.
This is how I solved setting a custom height for the iframe:
Embedded iframe:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description"
content="Web site" />
<title>Test with embedded iframe</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<iframe id="ifrm" src="https://localhost:44335/package/details?key=123" width="100%"></iframe>
<script type="text/javascript">
window.addEventListener('message', receiveMessage, false);
function receiveMessage(evt) {
console.log("Got message: " + JSON.stringify(evt.data) + " from origin: " + evt.origin);
// Do we trust the sender of this message?
if (evt.origin !== "https://localhost:44335") {
return;
}
if (evt.data.type === "frame-resized") {
document.getElementById("ifrm").style.height = evt.data.value + "px";
}
}
</script>
</body>
</html>
iframe source, example from Create React App but only HTML and JS is used.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description"
content="Web site created using create-react-app" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript">
//Don't run unless in an iframe
if (self !== top) {
var rootHeight;
setInterval(function () {
var rootElement = document.getElementById("root");
if (rootElement) {
var currentRootHeight = rootElement.offsetHeight;
//Only send values if height has changed since last time
if (rootHeight !== currentRootHeight) {
//postMessage to set iframe height
window.parent.postMessage({ "type": "frame-resized", "value": currentRootHeight }, '*');
rootHeight = currentRootHeight;
}
}
}
, 1000);
}
</script>
</body>
</html>
The code with setInterval can of course be modified but it works really well with dynamic content. setInterval only activates if the content is embedded in a iframe and postMessage only sends a message when height has changed.
You can read more about Window.postMessage() here but the description fits very good in what we want to achieve:
The window.postMessage() method safely enables cross-origin
communication between Window objects; e.g., between a page and a
pop-up that it spawned, or between a page and an iframe embedded
within it.
Normally, scripts on different pages are allowed to access each other
if and only if the pages they originate from share the same protocol,
port number, and host (also known as the "same-origin policy").
window.postMessage() provides a controlled mechanism to securely
circumvent this restriction (if used properly).
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
If you want 100% width and height for iframe I would do it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description"
content="Web site" />
<style>
body {
margin: 0; /* Reset default margin */
}
iframe {
display: block; /* iframes are inline by default */
background: #000;
border: none; /* Reset default border */
height: 100vh; /* Viewport-relative units */
width: 100vw;
}
</style>
<title>Test with embedded iframe</title>
</head>
<body>
<iframe src="https://localhost:44335/package/details?key=123"></iframe>
</body>
</html>
Source:
https://stackoverflow.com/a/27853830/3850405
It is possible to make a "ghost-like" IFrame that acts like it was not there.
See http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/
Basically you use the event system parent.postMessage(..) described in
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
This works an all modern browsers!
Here are several methods:
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
</body>
AND ANOTHER ALTERNATIVE
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>
TO HIDE SCROLLING WITH 2 ALTERNATIVES AS SHOWN ABOVE
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe>
</body>
HACK WITH SECOND CODE
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe>
</body>
To hide the scroll-bars of the iFrame, the parent is made "overflow:hidden" to hide scrollbars and the iFrame is made to go upto 150% width and height which forces the scroll-bars outside the page and since the body doesn't have scroll-bars one may not expect the iframe to be exceeding the bounds of the page. This hides the scrollbars of the iFrame with full width!
source: set iframe auto height
In case someone getting to here:
I had a problem with the solutions when I removed divs from the iframe - the iframe didnt got shorter.
There is an Jquery plugin that does the job:
http://www.jqueryscript.net/layout/jQuery-Plugin-For-Auto-Resizing-iFrame-iFrame-Resizer.html
I found this resizer to work better:
function resizer(id)
{
var doc = document.getElementById(id).contentWindow.document;
var body_ = doc.body;
var html_ = doc.documentElement;
var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
var width = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );
document.getElementById(id).height = height;
document.getElementById(id).width = width;
}
Note the style object is removed.
In jQuery, this is the best option to me, that really help me!! I wait that help you!
iframe
<iframe src="" frameborder="0" id="iframe" width="100%"></iframe>
jQuery
<script>
var valueSize = $( "#iframe" ).offset();
var totalsize = (valueSize.top * 2) + valueSize.left;
$( "#iframe" ).height(totalsize);
</script>
Clearly there are lots of scenarios, however, I had same domain for document and iframe and I was able to tack this on to the end of my iframe content:
var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';
This 'finds' the parent container and then sets the length adding on a fudge factor of 50 pixels to remove the scroll bar.
There is nothing there to 'observe' the document height changing, this I did not need for my use case. In my answer I do bring a means of referencing the parent container without using ids baked into the parent/iframe content.
function resizeIFrameToFitContent(frame) {
if (frame == null) {
return true;
}
var docEl = null;
var isFirefox = navigator.userAgent.search("Firefox") >= 0;
if (isFirefox && frame.contentDocument != null) {
docEl = frame.contentDocument.documentElement;
} else if (frame.contentWindow != null) {
docEl = frame.contentWindow.document.body;
}
if (docEl == null) {
return;
}
var maxWidth = docEl.scrollWidth;
var maxHeight = (isFirefox ? (docEl.offsetHeight + 15) : (docEl.scrollHeight + 45));
frame.width = maxWidth;
frame.height = maxHeight;
frame.style.width = frame.width + "px";
frame.style.height = frame.height + "px";
if (maxHeight > 20) {
frame.height = maxHeight;
frame.style.height = frame.height + "px";
} else {
frame.style.height = "100%";
}
if (maxWidth > 0) {
frame.width = maxWidth;
frame.style.width = frame.width + "px";
} else {
frame.style.width = "100%";
}
}
ifram style:
.myIFrameStyle {
float: left;
clear: both;
width: 100%;
height: 200px;
padding: 5px;
margin: 0px;
border: 1px solid gray;
overflow: hidden;
}
iframe tag:
<iframe id="myIframe" src="" class="myIFrameStyle"> </iframe>
Script tag:
<script type="text/javascript">
$(document).ready(function () {
$('myIFrame').load(function () {
resizeIFrameToFitContent(this);
});
});
</script>
This is how I would do it (tested in FF/Chrome):
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
$(iframe).height($(iframe).contents().find('html').height());
}
</script>
<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>
I know the post is old, but I believe this is yet another way to do it. I just implemented on my code. Works perfectly both on page load and on page resize:
var videoHeight;
var videoWidth;
var iframeHeight;
var iframeWidth;
function resizeIframe(){
videoHeight = $('.video-container').height();//iframe parent div's height
videoWidth = $('.video-container').width();//iframe parent div's width
iframeHeight = $('.youtubeFrames').height(videoHeight);//iframe's height
iframeWidth = $('.youtubeFrames').width(videoWidth);//iframe's width
}
resizeIframe();
$(window).on('resize', function(){
resizeIframe();
});
Javascript to be placed in header:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
Here goes iframe html code:
<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>
Css stylesheet
>
.spec_iframe {
width: 100%;
overflow: hidden;
}
For angularjs directive attribute:
G.directive ( 'previewIframe', function () {
return {
restrict : 'A',
replace : true,
scope : true,
link : function ( scope, elem, attrs ) {
elem.on ( 'load', function ( e ) {
var currentH = this.contentWindow.document.body.scrollHeight;
this.style.height = eval( currentH ) + ( (25 / 100)* eval( currentH ) ) + 'px';
} );
}
};
} );
Notice the percentage, i inserted it so that you can counter scaling usually done for iframe, text, ads etc, simply put 0 if no scaling is implementation
This is how I did it onload or when things change.
parent.jQuery("#frame").height(document.body.scrollHeight+50);
If you are looking for a no jQuery cross-origin solution, you might want to look at my idea:
<main id="container"></main>
<script>
fetch('https://example.com').then(response => {
return response.text();
}).then(data => {
const iframeContainer = window.document.getElementById('container');
const iframe = document.createElement('iframe');
iframe.frameBorder = 'none';
iframe.width = '100%';
iframe.addEventListener("load", function() {
iframe.height = iframe.contentWindow.document.body.scrollHeight;
})
const finalHtml = data;
const blob = new Blob([finalHtml], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
iframeContainer.appendChild(iframe);
})
</script>
The easiest way is to set the height for the iframe if you know what the height of the document is and if it's fixed.
Good afternoon
Is simple, i need the white box height and width fit with the iframe text, how i can do it?
function resizeIframe (iframeContentWidth, iframeContentHeight) {
var container = window.frameElement.parentElement;
if (container != parent.document.body) {
container.style.width = iframeContentWidth + 'px';
container.style.height = iframeContentHeight + 'px';
}
window.frameElement.style.width = iframeContentWidth + 'px';
window.frameElement.style.height = iframeContentHeight + 'px';
return;
}
html {
background-color: #fff
}
div {
background-color: #000;
display: inline-block;
}
<div>
<iframe src="http://190.216.202.35/rxp/mobilpxr.php?stopid=502102" height="85px" width="250px" scrolling="no" frameborder="0">
</div>
At first, it's good to know, how the elements you've used in your HTML work.
Every browser has its own default size for iframes, which is used, if the size is not given by attributes or CSS. Usually the size is nearby 300x200. The body of a document loaded into iframe adapts the width of the iframe it was loaded into, and the height is defined according to the content, if any sizing for the body haven't been defined.
A div element is a block level element, which by default takes a width of 100% of its parent element, and the height depends on the content height. However, this can be changed by setting a CSS property display: inline-block for a div, when the width will be set according to the content of a div.
There's no simple way at client side to detect the size of an arbitrary content to be loaded, before it has been parsed, hence we have to wait that happen. We can wait the iframe to finish loading and parsing on a parent page (= the page containing the iframe), or we can do that in the iframe itself. The latter simplifies referencing, so we'll use it in the following example, i.e. all the following code must be included in the file which is loaded to the iframe.
The body of the iframe:
<div>
<span class="title">Capri A2</span>
<br />
<span class="big">Rutas aquí: | P17 | E31 | T31 | E21</span>
</div>
Iframe resize in the iframe:
window.onload = function () {
var bodyWrapper = document.querySelector('div'),
size;
// Adapt the size of bodyWrapper to its content. If needed, an absolute size can be set too.
bodyWrapper.style.display = 'inline-block';
// Get the size information of bodyWrapper
size = bodyWrapper.getBoundingClientRect();
// Set the iframe size
frameElement.style.width = size.width + 'px';
frameElement.style.height = size.height + 'px';
// Done!
return;
}
Try this, hope it will resolve your issue.
Set iframe "height:auto"
Ok, I thought this would be really simple, but it's turning out not to be. I think I'm just messing something up in my HTML/CSS, but here goes.
I have a basic page like so:
HTML
<!DOCTYPE html>
<html>
<head>
<link href='test2.css' rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="test2.js"></script>
</head>
<body>
<div id="scroll"></div>
</body>
</html>
test2.css
* {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
width: 100%;
}
#scroll {
height: 100%;
width: 100%;
overflow: scroll;
background-color: black;
}
test2.js
$(document).ready(function() {
// my resolution is 1440x900
alert('innerwidth should be 1425');
// all of these return 1440
alert('body innerwidth: ' + $('body').innerWidth());
alert('document width: ' + $(document).width());
alert('window width: ' + $(window).width());
alert('scroll div innerwidth: ' + $('#scroll').innerWidth());
alert('document.documentElement.clientWidth: ' + document.documentElement.clientWidth);
alert('document.documentElement.scrollWidth: ' + document.documentElement.scrollWidth);
});
So I've got one element on the page... a div that takes up the entire screen, or rather it should be taking up the entire screen minus the scrollbars. Now, I've been doing some snooping on how to grab the width and height of a page without the scrollbars, but unfortunately, none of them return the proper value... which makes me believe I'm missing the boat in my HTML or CSS.
I looked at the following:
jquery - how to get screen width without scrollbar?
how to get the browser window size without the scroll bars
So what I need is for a method to return the value of my viewable screen minus the respective scrollbar value... so for my width, my value should be 1425 because the scrollbar is 15 pixels wide. I thought that's what innerWidth's job was, but apparently I'm wrong?
Can anyone provide any insight? (I'm running Firefox 24.)
EDIT
To add some background, I've got a blank page. I will be adding elements one by one to this page, and I need to use the width of the page when calculating the sizes for these elements. Eventually, this page will grow and grow until the scrollbar appears, which is why I'm trying to force the scrollbar there from the start, but apparently, that still doesn't do anything.
EDIT2
Here's something even more interesting... if I do document.getElementById('scroll').clientWidth, I get the proper innerWidth, but if I do $('#scroll').width() or $('#scroll').innerWidth(), they both return the max resolution... sounds like a jQuery bug.
I got this somewhere and would give credit if I knew where, but this has been succesfull for me. I added the result as padding when setting the html overflow to hidden.
Problem is that the scrollbar is a feature of the browser and not the web page self. Measurement should be done dynamically. A measurement with a scrollbar and a measurement without a scrollbar will resolve into calculating the difference in width.
Found the source: http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
scrollCompensate = function () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return (w1 - w2);
}
var htmlpadding = scrollCompensate();
The correct answer is in this post marked as accepted:
CSS media queries and JavaScript window width do not match
This is the correct code:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
Discovered a very hacky solution... by adding this before my alerts in test2.js, I get the proper width:
var p = $('body').append('<p style="height: 100%; width: 100%;"></p>');
alert(p.width());
$('body').remove('p');
And consequently, all of the alerts now have the proper width. I also don't even need overflow-y in the CSS if I do it this way. Curious why this solves it...
The real answer should be keeping the HTML and CSS as is, then using document.getElementById('scroll').clientWidth. Using clientWidth gets the viewable area minus the scrollbar width.
The correct width of the page is given by $(document).width().
Your problem is that you're using a scroll within the div (overflow: scroll).
Using $(document).width() the returned value is already discounting the visible width of the scroll, but how do you put a scroll within the div value returned is no longer the same.
As the width of the scroll is not standard and varies from system to system and browser to browser, it is difficult to solve.
I suggest you remove the scroll of the div and let the browser manage this by default in the body, then yes you have the correct width.
I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});
I am using tinymce editor in my page. What I want to do is to change the height of the editor dynamically. I have created a function:
function setComposeTextareaHeight()
{
$("#compose").height(200);
}
but that is not working.
My textarea is
<textarea id="compose" cols="80" name="composeMailContent" style="width: 100%; height: 100%">
I have tried all sorts of methods for changing the height but could not come to a resolution. Is there any thing that i am missing?
You can resize tinymce with the resizeTo theme method:
editorinstance.theme.resizeTo (width, height);
The width and height set the new size of the editing area - I have not found a way to deduce the extra size of the editor instance, so you might want to do something like this:
editorinstance.theme.resizeTo (new_width - 2, new_height - 32);
Try:
tinyMCE.init({
mode : "exact",
elements : "elm1",
....
To change size dynamically in your javascript code:
var resizeHeight = 350;
var resizeWidth = 450;
tinyMCE.DOM.setStyle(tinyMCE.DOM.get("elm1" + '_ifr'), 'height', resizeHeight + 'px');
tinyMCE.DOM.setStyle(tinyMCE.DOM.get("elm1" + '_ifr'), 'width', resizeWidth + 'px');
The following comes in from this other SO answer I posted:
None of the above were working for me in TinyMCE v4, so my solution was to calculate the height based on the toolbars/menu bar/status bar, and then set the height of the editor, taking those heights into consideration.
function resizeEditor(myHeight) {
window.console.log('resizeEditor');
myEditor = getEditor();
if (myEditor) {
try {
if (!myHeight) {
var targetHeight = window.innerHeight; // Change this to the height of your wrapper element
var mce_bars_height = 0;
$('.mce-toolbar, .mce-statusbar, .mce-menubar').each(function(){
mce_bars_height += $(this).height();
});
window.console.log('mce bars height total: '+mce_bars_height);
myHeight = targetHeight - mce_bars_height - 8; // the extra 8 is for margin added between the toolbars
}
window.console.log('resizeEditor: ', myHeight);
myEditor.theme.resizeTo('100%', myHeight); // sets the dimensions of the editable area
}
catch (err) {
}
}
}
In my case, I wanted the editor window to match the width and height of the actual window, since the editor would come up in a popup. To detect changes and resize, I set this to a callback:
window.onresize = function() {
resizeEditor();
}
It's a bit late but for Googler like me, check the autoresize plugin
tinymce.init({
plugins: "autoresize"
});
Options
autoresize_min_height : Min height value of the editor when it auto resizes.
autoresize_max_height : Max height value of the editor when it auto resizes.
I'm using tinymce 4.8.3.
I display the editor in a resizable modal dialog box.
I solved this using flexbox, shown here in SASS/SCSS:
// TinyMCE editor is inside a container something like this
.html-container {
height: 100%;
overflow: hidden;
}
.mce-tinymce {
// This prevents the bottom border being clipped
// May work with just 100%, I may have interference with other styles
height: calc(100% - 2px);
& > .mce-container-body {
height: 100%;
display: flex;
flex-direction: column;
& > .mce-edit-area {
flex: 1;
// This somehow prevents minimum height of iframe in Chrome
// If we resize too small the iframe stops shrinking.
height: 1px;
}
}
}
When the editor is initialized we have to tell it to put 100% height on the IFRAME. In my case I also have to subtract 2px else the right border is clipped off:
tinymce.init({
...
height: "100%",
width: "calc(100% - 2px)"
});
What ManseUK stated is almost correct.
The correct solution is:
$('#compose_ifr').height(200);
or in your case
$('#composeMailContent_ifr').height(200);
Update: maybe this is more what you are looking for:
// resizes editoriframe
resizeIframe: function(frameid) {
var frameid = frameid ? frameid : this.editor.id+'_ifr';
var currentfr=document.getElementById(frameid);
if (currentfr && !window.opera){
currentfr.style.display="block";
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
currentfr.height = 200 + 26;
}
else if (currentfr.Document && currentfr.Document.body.scrollHeight) { //ie5+ syntax
currentfr.height = 200;
}
styles = currentfr.getAttribute('style').split(';');
for (var i=0; i<styles.length; i++) {
if ( styles[i].search('height:') ==1 ){
styles.splice(i,1);
break;
}
};
currentfr.setAttribute('style', styles.join(';'));
}
},
In case someone finds this and also wants to change the height of the source code editor plugin.
You need to edit the following file:
\tiny_mce\plugins\code\plugin.min.js
Look out for the attribute called minHeigh and adjust it to your needs. The height you define there is not the height of the entire box, but it is not the height of the textarea either. It is something inbetween.
You can set it according to your height
tinymce.init({
height: "500px"
});
I test this solution on version 5 of TinyMCE.
For change the height of TinyMCE after page loaded, all you need is: your element id
$(function(){
var selectedElement = tinymce.get('Element id without sharp(#)');
selectedElement.settings.height = 700;
selectedElement.settings.max_height = 400;
selectedElement.settings.min_height = 1000;
});
Also you can use autoresize plugin for get better experience:
tinymce.init({
plugins: 'wordcount autoresize',
})
$(window).load(function () {
$('#YourID_ifr').css('height', '550px');
});