Change tinyMce editor's height dynamically - javascript

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');
});

Related

Add pixels to existing CSS element with Javascript

here is my trouble.
I'm using a plugin for a lightbox. For some reason, one of the divs is 28px too short. I've looked all over for a solution for this, but nobody seems to be having the same problem.
The solution I've come up with is to find that element (which I have) and create a javascript snippet that will add "28" to the existing number. The height and width is being calculated directly on the div, not in an element in a stylesheet.
Example:
<div id="colorbox" class="" style="padding-bottom: 57px; padding-right: 28px; position: absolute; width: 892px; height: 602px; top: 2234px; left: 500px;">
I want the Javascript code to add 28 pixels to the width and 55px to the height.
How would I go about doing this?
I would like to say that I'm not looking for just an answer; if you could explain it to me, that would be great. Thanks so much, guys!
Edit: this is how I called the JQuery
Also, this is where you can see the page with the gallery: http://olsencustomhomes.com.previewdns.com/designs/verona-2/#gallery
EDIT FOR KRIS:
Is this the right code? It's in my header
<script>
$(document).ready(function() {
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}
$(document).ajaxStop(function() {
changeSize();
});
});
</script>
Pretty straightforward application of jQuery, but I commented it up for you anyway:
//select the box element using jQuery
var box = $('#colorbox');
//get the current width and height
var curWidth = box.width();
var curHeight = box.height();
//set the width and height with modified values
box.width(curWidth + 28);
box.height(curHeight + 55);
fiddle: http://jsfiddle.net/579s2/
If you want to add height and width dynamically. Something like this should work:
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}changeSize();
Also if you want to insure your code is happens after the colorbox opens you could use .ajaxStop(); Also note, outerWidht() and outerHeight() will get colorbox width plus the padding and borders.
To fire function after ajax events are finished:
$(document).ajaxStop(function() {
changeSize();
});
Update:
Okay, it looks the function fires initially. You can see width is null because the colorbox has not opened. What you want to do is fire the function after the colorbox opens. That is where ajaxStop() would come into play. But it might actually be better to use the colorbox callback function:
But not after the colorbox opens. So try doing the ajaxStop() approach. Also note, if you do this you will need to remove changeSize(); after function changeSize() For example:
$(document).ready(function() {
function changeSize(){
// function stuff
}
$(document).ajaxStop(function() {
changeSize();
});
});
Or, Colorbox OnComplete:
$(".selector").colorbox({
onComplete:function(){
changeSize();
}
});
Update 2:
I am not sure where you are calling colorbox exactly. But I see you have this: Found here
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%'
});
});
So try:
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%',
onComplete:function(){
changeSize();
}
});
});

How to change div height if browser height is less than a given number of pixels?

I have a div that I want to be one of two sizes.
If browser window height is smaller than a given height, then it uses the smaller height for the div
However, if browser window height is larger than given height, then it uses larger height for the div
I tried the following code but it's not working. I need help to get it working.
Here is the jsbin: http://jsbin.com/oFIRawa/1
And here is the code I have so far:
page.html
<div id="theDiv"> </div>
style.css
#theDiv {
background: #000;
border: 2px solid #222;
width: 300px;
height: 400px;
margin: 50px auto 0 auto;
}
script.js
$(document).ready(function () {
// call the method one time
updateWindowSize();
// subscribe the method to future resize events
$(window).resize(updateWindowSize);
// variables
var updateWindowSize = (function(){
var minAllowedWindowHeight = 500;
var largerDivHeight = 400;
var smallerDivHeight = 300;
// actual updateWindowSize function
return function(){
var winHeight = $(window).height();
var newHeight = winHeight < minAllowedWindowHeight ? smallerDivHeight : largerDivHeight;
$('#theDiv').height(newHeight);
};
})();
});
You can do this in CSS my good sir. It's called responsive design!
#media (max-height:500px) {
Enter special css conditions for 500px height.
}
#media (max-height:200px) {
Enter special css conditions for 200px height.
}
This is more commonly used for max-width because it can tell us when someone is using a mobile device (something like 360px max-width), then we can modify our page to look nice on mobile. No fancy javascript needed!
var threshhold;
var smallerHeight = 50;
var largerHeight = 100;
if ($(window).height() < threshold)
$('#theDiv').height(smallerHeight);
else
$('#theDiv').height(largerHeight);
FIDDLE
Demo

JavaScript: Get window width minus scrollbar width

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.

Angular ng-grid row height

is there any way to apply the height of the row in ng-grid according to its content.
there is one option rowHeight which is changed the height of all row. But I want dynamic row height according to its content.
Following is the Plunker I have made, in this I have used cellTemplate to insert Education field, But I want to increase the row height according to education field detail.
http://plnkr.co/edit/tQJNpB?p=preview
According to this link it is not possible:
[1]https://github.com/angular-ui/ng-grid/issues/157
But if anyone find the solution.....
These classes will make the table act as actual table, using display table-row and table-cell.
.ngCell {
display : table-cell;
height: auto !important;
overflow:visible;
position: static;
}
.ngRow {
display : table-row;
height: auto !important;
position: static;
}
.ngCellText{
height: auto !important;
white-space: normal;
overflow:visible;
}
Please note that this is supported by IE8 and up. It's also overriding the entire ng grid classes so it will be wise to use on a "need to" base:
#myTableId .ngCell {...}
#myTableId .ngRow {...}
...
Researching this discovered that in my fix should call anonymous function $scope.resizeViewPort whenever it makes change to ngGrid data or should be called whenever the viewport rows are updated.
Examples are after angular performs updates to the rows via data from the ng-grid module. I've found these steps useful in my anonymous function for height only:
$scope.resizeViewPort = function { // and the two steps below
// retrieve viewPortHeight
var viewportHeight = $('ngViewPort').height();
var gridHeight = $('ngGrid').height();
// set the .ngGridStyle or the first parent of my ngViewPort in current scope
var viewportHeight = $('.ngViewport').height();
var canvasHeight = $('.ngCanvas').height();
var gridHeight = $('.ngGrid').height();
alert("vp:" + viewportHeight + " cv:" + canvasHeight + " gh:" + gridHeight);
var finalHeight = canvasHeight;
var minHeight = 150;
var maxHeight = 300;
// if the grid height less than 150 set to 150, same for > 300 set to 300
if (finalHeight < minHeight) {
finalHeight = minHeight;
} else if (finalHeight > viewportHeight) {
finalHeight = maxHeight;
}
$(".ngViewport").height(finalHeight);
}
I wanted to chime in on this question. I have followed up on this example and have used the solution provided by getuliojr. This solution seems to work pretty well, note that you will have to clone the fork and build the source in order to use in your app. I have a plunker live of it working: http://plnkr.co/edit/nhujNRyhET4NT04Mv6Mo?p=preview
Note you will also need to add 2 css rules:
.ngCellText{
white-space:normal !important;
}
.ngVerticalBarVisible{
height: 100% !important;
}
I have yet to test this under significant load or cross-browser but will update with more once I do.
GH Repo for ng-grid with flexible height by getuliojr: https://github.com/getuliojr/ng-grid/commits/master
None of these solutions will work completely. The height being fixed is assumed all through out the code. It is typical with row virtualization to assume this because you aren't loading up all the rows at once so its very difficult to tell the ultimate height of the grid. NGrid 3.0 is supposed to support dynamic row height but I'm not sure when it is expected to be ready.
Adapt-Strap. Here is the fiddle.
It is extremely lightweight and has dynamic row heights.
<ad-table-lite table-name="carsForSale"
column-definition="carsTableColumnDefinition"
local-data-source="models.carsForSale"
page-sizes="[7, 20]">
</ad-table-lite>
it's not the sexiest thing in the world and I doubt it's that performant but this does the trick:
function flexRowHeight() {
var self = this;
self.grid = null;
self.scope = null;
self.init = function (scope, grid, services) {
self.domUtilityService = services.DomUtilityService;
self.grid = grid;
self.scope = scope;
var adjust = function() {
setTimeout(function(){
var row = $(self.grid.$canvas).find('.ngRow'),
offs;
row.each(function(){
var mh = 0,
s = angular.element(this).scope();
$(this).find('> div').each(function(){
var h = $(this)[0].scrollHeight;
if(h > mh)
mh = h
$(this).css('height','100%');
});
$(this).height(mh)
if(offs)
$(this).css('top',offs + 'px');
offs = $(this).position().top + mh;
self.scope.$apply(function(){
s.rowHeight = mh;
});
});
},1);
}
self.scope.$watch(self.grid.config.data, adjust, true);
}
}
execute using plugins in options:
plugins: [new flexRowHeight()]

make iframe height dynamic based on content inside- JQUERY/Javascript

I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe's height. The iframe should not have scroll bars.
I have a wrapper div tag inside the iframe which basically is all the content. I wrote some jQuery to make the resize happen :
$("#TB_window", window.parent.document).height($("body").height() + 50);
where
TB_window is the div in which the Iframe is contained.
body - the body tag of the aspx in the iframe.
This script is attached to the iframe content. I am getting the TB_window element from the parent page. While this works fine on Chrome, but the TB_window collapses in Firefox. I am really confused/lost on why that happens.
You can retrieve the height of the IFRAME's content by using:
contentWindow.document.body.scrollHeight
After the IFRAME is loaded, you can then change the height by doing the following:
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
Then, on the IFRAME tag, you hook up the handler like this:
<iframe id="idIframe" onload="iframeLoaded()" ...
I had a situation a while ago where I additionally needed to call iframeLoaded from the IFRAME itself after a form-submission occurred within. You can accomplish that by doing the following within the IFRAME's content scripts:
parent.iframeLoaded();
A slightly improved answer to Aristos...
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
}
</script>
Then declare in your iframe as follows:
<iframe onload="resizeIframe(this)" ...
There are two minor improvements:
You don't need to get the element via document.getElementById - as you already have it in the onload callback.
There's no need to set the iframe.height = "" if you're going to reassign it in the very next statement. Doing so actually incurs an overhead as you're dealing with a DOM element.
Edit:
If the content in the frame is always changing then call:
parent.resizeIframe(this.frameElement);
from within the iframe after the update. Works for same origin.
Or to auto detect:
// on resize
this.container = this.frameElement.contentWindow.document.body;
this.watch = () => {
cancelAnimationFrame(this.watcher);
if (this.lastScrollHeight !== container.scrollHeight) {
parent.resizeIframeToContentSize(this.frameElement);
}
this.lastScrollHeight = container.scrollHeight;
this.watcher = requestAnimationFrame(this.watch);
};
this.watcher = window.requestAnimationFrame(this.watch);
I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).
So in the parent document, add an event listener:
window.addEventListener('message', function(e) {
var $iframe = jQuery("#myIframe");
var eventName = e.data[0];
var data = e.data[1];
switch(eventName) {
case 'setHeight':
$iframe.height(data);
break;
}
}, false);
And inside the iframe, write a function to post the message:
function resize() {
var height = document.getElementsByTagName("html")[0].scrollHeight;
window.parent.postMessage(["setHeight", height], "*");
}
Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:
<body onLoad="resize();">
Add this to the iframe, this worked for me:
onload="this.height=this.contentWindow.document.body.scrollHeight;"
And if you use jQuery try this code:
onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"
you could also add a repeating requestAnimationFrame to your resizeIframe (e.g. from #BlueFish's answer) which would always be called before the browser paints the layout and you could update the height of the iframe when its content have changed their heights. e.g. input forms, lazy loaded content etc.
<script type="text/javascript">
function resizeIframe(iframe) {
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
window.requestAnimationFrame(() => resizeIframe(iframe));
}
</script>
<iframe onload="resizeIframe(this)" ...
your callback should be fast enough to have no big impact on your overall performance
There are four different properties you can look at to get the height of the content in an iFrame.
document.documentElement.scrollHeight
document.documentElement.offsetHeight
document.body.scrollHeight
document.body.offsetHeight
Sadly they can all give different answers and these are inconsistant between browsers. If you set the body margin to 0 then the document.body.offsetHeight gives the best answer. To get the correct value try this function; which is taken from the iframe-resizer library that also looks after keeping the iFrame the correct size when the content changes,or the browser is resized.
function getIFrameHeight(){
function getComputedBodyStyle(prop) {
function getPixelValue(value) {
var PIXEL = /^\d+(px)?$/i;
if (PIXEL.test(value)) {
return parseInt(value,base);
}
var
style = el.style.left,
runtimeStyle = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft;
el.style.left = style;
el.runtimeStyle.left = runtimeStyle;
return value;
}
var
el = document.body,
retVal = 0;
if (document.defaultView && document.defaultView.getComputedStyle) {
retVal = document.defaultView.getComputedStyle(el, null)[prop];
} else {//IE8 & below
retVal = getPixelValue(el.currentStyle[prop]);
}
return parseInt(retVal,10);
}
return document.body.offsetHeight +
getComputedBodyStyle('marginTop') +
getComputedBodyStyle('marginBottom');
}
Other answers were not working for me so i did some changes. Hope this will help
$('#iframe').on("load", function() {
var iframe = $(window.top.document).find("#iframe");
iframe.height(iframe[0].ownerDocument.body.scrollHeight+'px' );
});
Just in case this helps anyone. I was pulling my hair out trying to get this to work, then I noticed that the iframe had a class entry with height:100%. When I removed this, everything worked as expected. So, please check for any css conflicts.
I am using jQuery and the code below working for me,
var iframe = $(window.top.document).find("#iframe_id_here");
iframe.height(iframe.contents().height()+'px' );
You can refer related question here - How to make width and height of iframe same as its parent div?
To set dynamic height -
We need to communicate with cross domain iFrames and parent
Then we can send scroll height/content height of iframe to parent window
And codes - https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8
Rather than using javscript/jquery the easiest way I found is:
<iframe style="min-height:98vh" src="http://yourdomain.com" width="100%"></iframe>
Here 1vh = 1% of Browser window height. So the theoretical value of height to be set is 100vh but practically 98vh did the magic.
All other answers are correct but what if the iframe has some dynamic content like a map that loads later and dynamically changes your iframe scroll height. This is how I achieved it.
var iFrameID = document.getElementById('idIframe');
intval = setInterval(function(){
if(iFrameID.scrollHeight == iFrameID.contentWindow.document.body.scrollHeight){
clearInterval(intval);
}else{
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
},500)
I simply wrap the code inside setInterval which matches the iframe scroll height with iframe content scroll height then clear the interval.
in my project there is one requirement that we have make dynamic screen like Alignment of Dashboard while loading, it should display on an entire page and should get adjust dynamically, if user is maximizing or resizing the browser’s window.
For this I have created url and used iframe to open one of the dynamic report which is written in cognos BI.In jsp we have to embed BI report. I have used iframe to embed this report in jsp. following code is working in my case.
<iframe src= ${cognosUrl} onload="this.style.height=(this.contentDocument.body.scrollHeight+30) +'px';" scrolling="no" style="width: 100%; min-height: 900px; border: none; overflow: hidden; height: 30px;"></iframe>
I found the answer from Troy didn't work. This is the same code reworked for ajax:
$.ajax({
url: 'data.php',
dataType: 'json',
success: function(data)
{
// Put the data onto the page
// Resize the iframe
var iframe = $(window.top.document).find("#iframe");
iframe.height( iframe[0].contentDocument.body.scrollHeight+'px' );
}
});
To add to the chunk of window that seems to cut off at the bottom, especially when you don't have scrolling I used:
function resizeIframe(iframe) {
var addHeight = 20; //or whatever size is being cut off
iframe.height = iframe.contentWindow.document.body.scrollHeight + addHeight + "px";
}
This one is useful when you require a solution with no jquery. In that case you should try adding a container and set a padding to it in percentages
HTML example code:
<div class="iframecontainer">
<iframe scrolling="no" src="..." class="iframeclass"width="999px" height="618px"></iframe>
</div>
CSS example code:
.iframeclass{
position: absolute;
top: 0;
width: 100%;
}
.iframecontainer{
position: relative;
width: 100%;
height: auto;
padding-top: 61%;
}
The simple solution is to measure the width and height of the content area, and then use those measurements to calculate the bottom padding percentage.
In this case, the measurements are 1680 x 720 px, so the padding on the bottom is 720 / 1680 = 0.43 * 100, which comes out to 43%.
.canvas-container {
position: relative;
padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
height: 0;
overflow: hidden;
}
.canvas-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
A slightly improved answer to BlueFish...
function resizeIframe(iframe) {
var padding = 50;
if (iframe.contentWindow.document.body.scrollHeight < (window.innerHeight - padding))
iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
else
iframe.height = (window.innerHeight - padding) + "px";
}
This takes in consideration the height of the windows screen(browser, phone) which is good for responsive design and iframes that have huge height.
Padding represents the padding you want above and below the iframe in the case it goes trough whole screen.
jQuery('.home_vidio_img1 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery(this).replaceWith(video);
});
jQuery('.home_vidio_img2 img').click(function(){
video = <iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>;
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
jQuery('.home_vidio_img3 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
jQuery('.home_vidio_img4 img').click(function(){
video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
jQuery('.home_vidio_img1 img').replaceWith(video);
jQuery('.home_vidio_img1 iframe').replaceWith(video);
});
Sample using PHP htmlspecialchars() + check if height exists and is > 0:
$my_html_markup = ''; // Insert here HTML markup with CSS, JS... '<html><head></head><body>...</body></html>'
$iframe = '<iframe onload="if(this.contentWindow.document.body.scrollHeight) {this.height = this.contentWindow.document.body.scrollHeight;}" width="100%" src="javascript: \''. htmlspecialchars($my_html_markup) . '\'"></iframe>';
Script
<script type="text/javascript" language="javascript">
$(document).ready(function(){
var height = $(window).height();
$('.myIframe').css('height', height - 200);
});
</script>
iframe
<iframe class="myIframe" width="100%"></iframe>
It's working in my case.
$(document).height() // - $('body').offset().top
and / or
$(window).height()
See Stack Overflow question How to get the height of a body element.
Try this to find the height of the body in jQuery:
if $("body").height()
It doesn't have a value if Firebug. Perhaps that's the problem.
just make iframe container position:absolute and iframe will automatically change its height according to its content
<style>
.iframe-container {
display: block;
position: absolute;
/*change position as you need*/
bottom: 0;
left: 0;
right: 0;
top: 0;
}
iframe {
margin: 0;
padding: 0;
border: 0;
width: 100%;
background-color: #fff;
}
</style>
<div class="iframe-container">
<iframe src="http://iframesourcepage"></iframe>
</div>

Categories

Resources