Shaunwithanau
Shaunwithanau

Reputation: 585

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.

Upvotes: 0

Views: 353

Answers (5)

Mahesh Velaga
Mahesh Velaga

Reputation: 21991

try div.offsetHeight || div.clientHeight

Upvotes: 4

ajm
ajm

Reputation: 20105

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.

Upvotes: 2

plodder
plodder

Reputation: 2306

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)

Upvotes: 3

Chris Doggett
Chris Doggett

Reputation: 20757

Use jQuery:

height()

width()

Upvotes: -1

Dustin Laine
Dustin Laine

Reputation: 38503

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

Upvotes: 3

Related Questions