Getting div height - javascript

Firebug tells me the computed style of my_div:
width 300px
height 453.167px
Yet when I execute console.log(mydiv.style.height), it gives me an empty string, even though console.log(mydiv) logs the correct element. I am sure the page has loaded by the time this logging code is called. I'd appreciate a solution that does not use jQuery.

Depending on the browser of choice, one of these will do:
mydiv.offsetHeight
mydiv.clientHeight
Get full height of a clipped DIV
Getting the height of a div

UPDATE:
Many browser inconsistencies have been fixed since my original answer. Now the clientHeight property of a DOM element is reliable.
var height = element.clientHeight;
The Element.clientHeight read-only property is zero for elements with no CSS or inline layout boxes, otherwise it's the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.
clientHeight can be calculated as CSS height + CSS padding - height of horizontal scrollbar (if present).
Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect().
Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
Original answer:
If you use the jQuery JS library, you can just do this:
var computed_height = $('#my_div').height();
If you use the Prototype JS library, it's similar:
var computed_height = $('my_div').getHeight();
Using a library is often the easiest & most cross-browser way to do something. Getting computed styles with vanilla js is unreliable because the properties are different across browsers.

Related

Aurelia JS - Kendo UI vertical sliders with height in percent?

I've taken a version of the code posted on Aurelia JS - iterate through children (kendo UI) elements? and modified it slightly, here:
https://gist.run/?id=323de53223d2ec872f17361378639556
I would basically like to express that the vertical sliders should be 90% of the height of the enclosing div; note that:
If there is no CSS height: specification, the sliders get some height, and that is it
If I set the CSS height (either via div.eqSlider in basic-use.css, or as an inline style attribute) in either px or em, then all is fine
But, if I set the CSS height in percent % (either via div.eqSlider in basic-use.css, or as an inline style attribute), or to calc(90%-10px) or similar - then the display is completely messed up, as shown on the image below:
So, is it somehow possible to set the height of these sliders to 90% of the height of the enclosing div - and if so, how?
Ok, I think I fixed it - the problem was as is typical in these cases: by default, divs and such don't have a height defined, and their height gets computed based on their contents. Since the sliders in the example are the content, without any other further specification, their height in procent then either becomes recursive, or is percentage of height 0.
Which is why then one must ensure that the entire chain from body to the enclosing div have a height defined in % (in essence, 100%, except it may show scrollbar). And I thought I had done that in the previous example - but I made a mistake in the .css: I used a .example selector (for a class), whereas I should have used #example selector (for an id); and that broke the height calculation of the chain of nested divs.
I noticed that once I assigned borders to each and every div in the nested chain; and then could correct so they all have defined height. Once all of the divs - and thus the enclosing one - have a height, then the sliders can get a height in percent, either in the .css file, or by assignment from JavaScript (via slider.wrapper.css("height", "50%");)
And so, the corrected code is now on:
https://gist.run/?id=fcfc066733ad903fa0575388a1637e4f
... and the output looks as expected:

methods for element width/height

Question: Is there a scenario where getBoundingClientRect and window.getComputedStyle would differ in width or height?
I just found a inconsistent width (see under) in IE when a element has box-sizing where window.getComputedStyle returns the wrong value.
So I thought about overriding just width and height with values from getBoundingClientRect but not sure if there are cases where that would fail.
Example of the problem (broken in IE): http://jsfiddle.net/bwPM8/
var box = document.querySelector('.box');
var gBCR_width = box.getBoundingClientRect().width; // always 200
var wGCS = window.getComputedStyle(box).width; // 200 some browsers, 160 in IE
Yes, there are several differences between these two functions.
getBoundingClientRect() will return a text rectangle object that encloses a group of text rectangles (the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element). The latter, getComputedStyle(), will return the computed CSS style of that element, after applying all CSS.
Therefore the resulting width and height can be drastically different.
For instance, by simply applying a transform to that element you already change the width that is returned by getBoundingClientRect():
http://jsfiddle.net/epW3c/
Moreover, even if you add a border or padding to your element, the width and height will be different in both cases.
Depending on the version of IE you're testing this on, you might be experiencing the infamous Internet Explorer box model bug which causes the interpretation of the dimensions of the element to be wrong. Make sure you're not running your page in quirks mode by adding the doctype properly.
In IE the CSS padding: 10px; cause overflow and that gives you extra size of the computedStyle..
Also IE calculates Borders separately from the object.
This sums up the answer with difference of 40px
Now with overflow:hidden; OR box-sizing: border-box; that cause value go in minus so will become 200px - 40px = 160px.
Note: Here if we remove overflow:hidden will not make any difference as the box-sizing:border-box cause the design not to grow further from defined height and width.
I have generate another fiddle 1 (without padding) which gives
'computedValue : 180px'
And with Border:0px the fiddle 2 give results
same as in other browser..
I hope this clears what causes what in IE(IE has its own mind that sometimes cause pain to developers)

How to change the width/height element, which has settings in subclass

I've a trouble with the style of nav element in my web application.
As you're able to see, if to focus on element nav#menu.horizontal-menu - I can see the actual width/height of that element in Chrome.
BUT! When I try to obtain that element in JavaScript by the id - menu (as you can see the tag declaration of nav tag in the bottom part of screen):
There is no both width or height values of it...
I rather understand, that it may be because of:
`nav#menu.horizontal-menu` != `nav`
But, it's only my suggestion... I've tried then to use both functions:
getElementsByClassName()
querySelector()
But... also no success as you can see in screens, what's wrong and how to get so needed actual width and height options from element?
Thanks!
I think you are looking for this answer:
How do I retrieve an HTML element's actual width and height?
.style.width only checks what is filled in in the style attribute of the element. OffsetWidth would probably work...
That's because there are no width and height styles defined for it.
To calculate the rendered width and height, use a.offsetWidth and a.offsetHeight. Those are the values that DevTools are showing on hover.
Have you tried:
var width = document.getElementById('foo').offsetWidth;
var height = document.getElementById('foo').offsetHeight;
For cross-browser compatibility I'm recommending you to use jQuery

JavaScript - Need a way to set OuterHeight of the Element

I have an container element which is sort of a layout container for its children and based on some attributes I have to arrange children.
I need simple way to set outerHeight of an element, something like,
$(e).setOuterHeight(200);
jQuery's outerHeight does not set the height at all, indeed its a readonly method.
$(e).height(200); // this clips my element
In above method, I loose borders of input of type text.
My element's children are docked based on available space and some other criteria based on data that it holds, simple layouts like float,clear etc will not work because padding etc change dynamically based on sizes. I will finally end up using Table, even if I dont want to but have no choice, but anyway thanks for the help.
Now when element is sized to more then children then there is no problem, but sometimes container element may have lesser height then the children and that time, I need to increase the size.
function calculateSize(e){
var s = {
width: $(e).innerWidth(),
height: 0
};
var ae = new Enumerator(e.children);
while(ae.next()){
var child = ae.current();
// I have tried all alternatives
// for following lines
// child.clientHeight || child.offsetHeight
// $(child).outerHeight()
// $(child).innerHeight()
s.height += $(child).outerHeight();
}
if(s.height > $(e).height()){
$(e).height(s.height);
}
}
function layoutChildren(e){
....
/// for every child c
/// some steps before
var heightForChildren =
calculatedWithPadMarginBorder(availableHeight,c);
/// tried combinations
$(c).height(heightForChildren);
/// last statement fails for button
/// as button's padding cuts itself
/// removing padding in calculation
/// cuts other input elements !!
/// some steps after
....
}
I need some explanation of how to calculate runtime height/width including/excluding padding/margin/border etc and how to set it correctly so that I dont run into problems. I cant keep on trying all permutations combinations as I dont see a correct documentation even on jQuery website.
Fixed height calculations are fine, but this is kind of a dynamic element which resizes itself and arranges children in specific order.
Problem is there is no way to set outerHeight, when we set height/width of an element, the height/width is actually inner height/width without taking margin into consideration, while when we want to resize parent, we need outerHeight, but we cannot set back the outerHeight that easily.
My calculateSize and layoutChildren are two separate methods and two separate algorithms because parent will be resized to sum of all children's height. And then height is simply divided by no. of children stacked one above other. My calculation is perfect, but in my layoutChildren method I have "outerHeight" and "outerWidth" of element and have no idea on how to set it correctly by using jQuery or any other way.
.outerHeight( value )
version added: 1.8.0
you can use jQuery.outerHeight(value) to set the value of an element's outer height. Ex: $foo.outerHeight( 200 )
If you don't have a special requirement, a standard element by default sizes its height to match its children. If you style the to float:left or float:right its default width will then also be that to contain all its children.
Ok, this is strange but this is the Answer.
There are weird controls,
SELECT
BUTTON (INPUT[type=submit|reset|button])
WebKit Browsers
Padding and Border are considered as part of OuterWidth for all controls
Padding and Border must be added to Width as OuterWidth for all controls
Padding and Border are considered as part of InnerWidth for "weird controls"
Padding and Border must be subtracted from Width before setting the Width for all "non weird controls"
Non WebKit Browsers
Padding and Border are considered as part of OuterWidth for all non "weird controls"
Padding and Border must be added to Width as OuterWidth for all non "weird controls"
Padding and Border are considered as part of InnerWidth for all non "weird controls"
Padding and Border must be subtracted from Width before setting the Width for all "non weird controls"
I would be happy to help, but I simply do not understand your question.
In regards to the documentation of the dimensions methods of jQuery I found that http://api.jquery.com/category/css/ holds documentation on both innerWidth(), innerHeight(), outerWidth() and outerHeight().
I hope this helps, otherwise, try reading through your question, making it more obvious what you need the answer for.

How do I get a useful value for height and width of a div element using javascript?

I need to be able to store the current height and width of a div at any point in time.
Currently I am using div.style.height/width which works fine when the styling is applied inline.
The problem is that this returns for example 600px and not 600.
Is there a better way to do this? If not, whats the best way to get just the number 600?
My updated code looks like this:
var div = document.getElementById('container');
div.scrollLeft = contentdim.cx*scalar - parseInt(div.style.width)/2;
div.scrollTop = contentdim.cy*scalar - parseInt(div.style.height)/2;
Which works fine in FF. For some reason scrollTop is messing up in Chrome though..
Note: This is a function which is called onscroll for the div.
try div.offsetHeight || div.clientHeight
parseInt(div.style.height) is more generic than div.style.height.replace("px","")
However div.style.offsetHeight might be better because it does not rely on style being explicitly set (but you have to render the div before you can read the value)
div.style.height.replace("px","")
With jQuery, a bit more elegant, you can do it as well: http://api.jquery.com/height/
$("div").height()
//returns just the integer
To summarize the above:
document.getElementById('yourElement').style.height
CSS height if it has been set in a stylesheet. Will not include padding, margin, etc. If it is not set, you may wind up with values like auto.
document.getElementById('yourElement').offsetHeight
Height of the HTMLElement as rendered in the browser, including padding, scrollbars etc. (The total offset this Element's height consumes). Note that this often can be equivalent to clientHeight but that is not guaranteed.
Here is how offsetHeight is defined on Mozilla Developer Center. Note that there are a few differences with clientHeight, namely clientHeight does not include rendered scrollbars; offsetHeight will generally give you the maximum value.
Use jQuery:
height()
width()

Categories

Resources