Javascript offsetWidth returning undefined - javascript

I have a JS function that gets the width of a div on my page:
function getWidth() {
var container = document.getElementsByClassName('tag');
var message = "The width of the contents width padding: " + container.width + "px.\n";
alert(message);
}
The function doesn't run until page is loaded:
<body onload="getWidth()">
And the div is defined in CSS as a percentage, with a max-width of 900px, which is what the output should be. But instead, I'm getting this alert:
The width of the contents width padding: undefinedpx.
I've looked around for an answer, but it looks like this should be work. Any reason why it's not working?

getElementsByClassName returns a collection of nodes.
You are acting like it is one.
You would need to select the index.
var container = document.getElementsByClassName('tag')[0];

Related

How to reproduce the `.width()` jQuery behavior in pure JavaScript, without another library/framework

I know the method .width() from jQuery returns the element's width without padding, border and margin.
In the accepted answer Table with vertical scroll, in which I can't comment, such method is used to get the width of the td elements of the first row of the table.
One of the jsFiddle in the answer there can be used to see the values returned by the method.
I tried to reproduce the behavior with this piece of code:
let colunas = document.querySelector('.scroll tbody tr:first-child').children;
let colunasWidth = [];
for (let i = 0, length = colunas.length; i < length; i++) {
colunasWidth.push(colunas[i].offsetWidth);//Width/clientWidth
}
I tried the various widths (offsetWidth, width, clientWidth), none gave the same result as jQuery and then I tried to get the border and padding width to subtract from such various widths, but I can't think of a way to get the math or right properties right.
Is there a simple and straightfoward way to do it?
You want window.getComputedStyle and .getPropertyValue
What it does is, it gets the styles used and then gets the actual width value of the element.
Here's a jsfiddle to show you: http://jsfiddle.net/u9d27wno/1/
var jquerywidth = $("#container").width();
var jqueryishwidth = window.getComputedStyle(document.getElementById("container"));
var offsetWidth = document.getElementById('container').offsetWidth;
var clientWidth = document.getElementById('container').clientWidth;
var msg = "offsetWidth: " + offsetWidth + "<br>\n";
msg += "clientWidth: " + clientWidth + "<br>\n";
msg += "jQuery width: " + jquerywidth + "<br>\n";
msg += "jQueryish width: " + jqueryishwidth.getPropertyValue("width") + "<br>\n";
document.getElementById('msg').innerHTML = msg;
//alert(document.getElementById('msg').innerHTML);
Let me know if that's the solution you needed!
You can use element.clientWidth and getComputedStyle together, to obtain teh value you are looking for...
element.clientWidth
The Element.clientWidth property is zero for elements with no CSS or inline layout boxes, otherwise it's the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.
window.getComputedStyle
The window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain.
function width(el){
// get element computed styles
let styles=getComputedStyle(el);
// remove the 'px' from the returned values
let paddingLeft = styles['padding-left'].slice(0,-2);
let paddingRight= styles['padding-right'].slice(0,-2);
// substract paddings from value returned by clientWidth, and return value
return el.clientWidth - paddingLeft - paddingRight;
}
// test
let w = width(document.getElementById('test'))
console.log( 'VanillaJS:' , w )
console.log( 'JQuery : ', $('#test').width())
#test{
border:10px solid red;
width:200px;
margin:10px;
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
I'm 200px + <br>
10px padding + <br>
10px border +<br>
10px margin
</div>

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"

JQuery - waiting until image loaded not working

I need to get the height of an image on the page and try to do so only after the image has been loaded. However, it seems like I'm still getting a height of 0 for some of the images on the page. Here's my code:
carousel_img.on('load', function(){
setCarouselImageMargins(carousel_img, carousel_width);
});
function setCarouselImageMargins(image, width){
var carousel_left_margin = (image.width()-parseInt(width))/2*-1;
image.css('margin-left', carousel_left_margin);
console.log('carousel image width: ' + image.width()); // this is returning 0
console.log('carousel_left_margin: ' + carousel_left_margin);
}
Is there another way to ensure the image is fully loaded on the page?
you can do it after
$( document ).ready(function() {
setCarouselImageMargins(carousel_img, carousel_width);
});
You can use clientWidth and clientHeight DOM properties to get the inner dimension of a DOM element in your case image. So in your scenario, it will get the actual dimension of the visible image
var image = document.getElementById('imageid');
//or however you get a handle to the IMAGE
var width = image.clientWidth;
var height = image.clientHeight;

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.

set the width dynamically of element which create dynamically

I create one div#sresult_container dynamically and append no of div to that div. and all appended div have different text. so i can retrieve the width of div#sresult_container but i try to that increase the width of div#sresult_container 10px before it display on the view port. how can i do this plese help me?
my code is below:
var $sresult_container = $('<div id="sresult_container"></div>');
AND after that i append the some divs as children of div#sresult_container.
and append to body.
$('body').append($sresult_container);
var Setwidth = $('#sresult_container').outerWidth() + 10;
$('#sresult_container').css('width',Setwidth + 'px');
so here first load original width after that load the modified width. so how can do directly load the modified width.
First of all #sresult_container must have a pre-defined width.
#sresult_container {
width: 100px;
}
$('<div id="sresult_container">text</div>').appendTo('body');
$('#sresult_container').css('width', function () {
return ($(this).outerWidth(true) + 10) + 'px';
});​
http://jsfiddle.net/xBZT7/14/
http://jsfiddle.net/xBZT7/15/

Categories

Resources