Using the height() method in jquery

102 views Asked by At

I am new to jquery and am currently trying to set a variable equal to the height of some div with id="thing" before animating another div with class=".init_leftbar" by the same quantity.

var iHeight = $("#thing").height();

$(".init_leftbar").animate({top: iHeight + "px"});

However, this does not seem to be working.

if I just set "iHeight" equal to some number it will animate however.

I figured there has been some misunderstanding on my part as to how the "height()" method works.

Any help is greatly appreciated.

4

There are 4 answers

2
Romeo On BEST ANSWER

I would try to print $("#thing").height() in the browser console with

console.log($("#thing").height());

to see what is returning from the div. I also noticed that .height() has some problems with absolute positioned divs given a display:block; style.

1
Collin On

As documented in the Jquery API:

http://api.jquery.com/height/

// Returns height of browser viewport
$( window ).height();

// Returns height of HTML document
$( document ).height();
0
Polyducks On

Consider running the script on document ready, allowing everything else to load first.

Also, you might get better mileage with outerheight(), which accounts for everything which can make up the height, including padding.

0
Dudi On

What about replacing:

$("#thing").height();

with:

$('#thing').css("height");

Be aware that css() returns string as "100px" and not 100 as height() so you need to delete the '+ "px"' suffix.