iframe height for values lower than 150px - javascript

I want to change the iframe height based on how the iframe content changes, but I'm having problems if the iframe's content has a height value lower than 150px.
I've tested this code in Firefox and Chrome and it has the same result.
Here you can test it https://jsfiddle.net/bqvc0pp5/17/
From what I've seen if no height is specified the iframe will automatically have 150px(without border).
In this example I increased the value to 300px then lowered to 200px than to 50px . Everything works great until the 50px is converted to 150px;
var iframe = document.createElement('iframe');
iframe.setAttribute("scrolling","no");
iframe.onload = () => {
builtElement();
};
//append iframe to main document
document.body.appendChild(iframe);
var k=0;
function builtElement(){
var div = document.createElement('div');
div.style.height="50px";
div.style.backgroundColor="salmon";
iframe.contentWindow.document.body.style.margin="0px";
iframe.contentWindow.document.body.appendChild(div);
div.addEventListener("click", () =>{
if(k==0){
div.style.height="300px";
}
if(k==1){
div.style.height="200px";
}
if(k==2){
div.style.height="50px";
}
if(k>=2) k=0;
else k++;
updateIframeHeight();
});
}
function updateIframeHeight(){
//I need to reset height or else scrollHeight will be the last max value
iframe.style.height="";
var height = iframe.contentWindow.document.body.scrollHeight;
//this is a dirty hack where I can check if offsetHeight is lower than 150px
var offsetHeight = iframe.contentWindow.document.body.offsetHeight;
//if(offsetHeight<150) height=offsetHeight;
console.log("scrollHeight: "+height);
console.log("scrollHeight: "+offsetHeight);
iframe.style.height=height+"px";
}
If I do a little hack and check if the offsetHeight is lower than 150px it works.
var offsetHeight = iframe.contentWindow.document.body.offsetHeight;
if(offsetHeight<150) height=offsetHeight;
Is this the best way to do this?
UPDATE: In a real example, the iframe body contains more than one elements, but only certain elements change height, therefor changing the body scrollHeight

I found the solution. All you have to do is set the size to 0px;
iframe.style.height="0px";
What I did previously iframe.style.height=""; set the height to 150px by default. It appears that if no size is specified the iframe size will be 150px;

this is not the final solution but this may help you to fix your issue without hacks:
[Fiddle][1]https://jsfiddle.net/Marouen/qskpdn8b/

Related

Containing element's width is not displayed correctly

Several images are placed into an element whose display is flex and flex-wrap set to nowrap. The images don't fit into the element's width and extend beyond the screen width.
I am trying to calculate the width of the element that includes the images. However the width of element is always equal to screen width whereas it should be much greater than screen width.
Several threads have advised to first check if all the images have been loaded. Following is the code used to check the loading of the images.
let len = allCarousalImagesList.length,
counter = 0;
[].forEach.call( allCarousalImagesList, function( img ) {
if(img.complete)
incrementCounter();
else
img.addEventListener( 'load', incrementCounter, false );
} );
function incrementCounter() {
counter++;
if ( counter === len ) {
let carousalWidth = carousalElement.offsetWidth;
let browserWidth = window.innerWidth;
console.log(browserWidth, carousalWidth);
}
}
Inspite of checking for the loading of images, the width of the element containing unwrapped images is not being displayed correctly and is equal to screen width. I am using offsetWidth to get the width. Please help with this issue.
The code has been uploaded on the codesandbox here
So I created a solution to your problem:
And make sure to add position:absolute; to your carousal class
window.addEventListener("load", function () {
let carousalElement = document.getElementsByClassName("carousal")[0];
var width_of_img_container = window.getComputedStyle(carousalElement).width;
console.log(width_of_img_container);
},false);
Hope I could help.

the size of an iframe don't fit the real content

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"

(Javascript/CSS) resizing function not working

I have a container div that has to fit in two different types of pictures. Some pictures are 'potrait', width:533px and height:801px, others are 'landscape', width:800px and height:533px.
So to make the div size change to accommodate for the pictures, I wrote the function described below (the 'photos' var is an array of pictures and the [i] is a variable for changing through them and 'img' is a var that fetches the #container element)
function resize() {
var width = photos[i].clientWidth;
var height = photos[i].clientHeight;
if (width + height === 1333) {
img.style.width="800px";
img.style.height="533px";
}
else if (width + height === 1334) {
img.style.width="533px";
img.style.height="801px";
}
}
Then, I placed this function in the next and back functions for switching between the pictures,
function next() {
img.src = photos[i];
el.innerHTML = caption[i];
resize();
if (i<photos.length-1){
i=i+1;
} else {
i=0;
}
}
The next and back functions work, but when they get to the pictures that needed to be resized, the container holds the same dimensions that were preset in the CSS.(the preset widht/height in the CSS is for the landscape pictures, because I only have 2 potrait pictures that the div needs to change its size to.
#container {
height: 533px;
width: 800px;
overflow:hidden;
}
I tried looking at other resize threads but whereas people have needed a way to get only a dynamic width or height, I need both to be that way. I think the problem lies in the "clientWidth/Height" property which I thought gets the width/height of the object before the '.' And i'm not sure if I should set the CSS container div to have a height or leave it to "auto" or a certain percentage. I'd appreciate any help on the matter :)

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.

scrollHeight not resetting after programmatically changing content

I am trying to learn a few things without jQuery. Here is one of the challenges I'm facing.
I have a fixed contenteditable div that when adding text to the div, if the scrollHeight exceeds the clientHeight I shrink the font until content fits the div.
Occasionally I "rebuild" the text which replaces the innerHTML programmatically. Or the user can delete text which should reduce the scrollHeight, but in both cases, the scrollHeight remains the maximum value. I need some way to increase the font size to "fit" the div again. (that ideally isn't super expensive)
Example:
My clientHeight = 142, and the scrollHeight = 158. A loop reduces the font size, until scrollHeight is 142.
Then, the user deletes a line of text, but the scrollHeight is still 142, no change.
code to reduce/increase height:
var textBox = document.getElementById('text');
var current, min = 6, max = 14;
current = textBox.style.fontSize.substr(0, textBox.style.fontSize.length - 2);
current = parseInt(current);
if (textBox.clientHeight < textBox.scrollHeight) {
while (textBox.clientHeight < textBox.scrollHeight) {
current--;
if (current < min) break;
textBox.style.fontSize = '' + current + 'pt';
}
} else if (textBox.clientHeight > textBox.scrollHeight) {
while (textBox.clientHeight > textBox.scrollHeight) {
current++;
if (current > max) break;
textBox.style.fontSize = '' + current + 'pt';
}
}
html (incase it matters):
<div id="text" contenteditable="true"></div>
css (incase it matters):
#text {
position: relative;
border: 1px solid blue;
top: 180px;
left: 31px;
width: 300px;
height: 132px;
padding: 5px;
font-family: 'mplantin';
font-size: 14pt;
font-weight: 200;
}
I was on the same boat, but with an iframe; I'm not sure if my solution suits your chat window because its for page transitioning, but after some testing this is my hack. "content" is the id of an iframe and this is executed inside a javascript function that is called when the page change is needed:
var c=document.getElementById("content");
c.width=0;
c.height=0;
c.src="page.html";
the `src' assignment method expands the values set to 0 right after, achieving the desired result; there may be a way for you to constantly re-size a text area like that; however, I had visual issues with you; I ended up using timers so that the change would take place while the transition between pages was transparent.
This seemed to fix my issue:
element.style.height = "auto";
both answers from #nixahn and #jeff are working for me (chrome,ff)
iframe.style.height ="0"; // or "auto"
iframe.contentWindow.document.open();
iframe.contentWindow.document.write('<style>'+css+'</style>');
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
I have used a div with a fixed height, and the problem with auto is that it resizes the element, I fixed that with the following code after my inner HTML was set:
element.style.height = "auto";
element.style.height = "400px";
now scrollHeight is resetted correctly and gives the real height of the inner HTML
I had this same issue -- A content editable div whose scrollHeight wouldn't shrink when lines were removed.
The accepted answer didn't fix the problem for me, however, removing the div's parent's display: flex; did.

Categories

Resources