1

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.

3
  • Nope, that's how it works, but if you have images or other content that need to load, you have to wait for it etc
    – adeneo
    Commented Jun 12, 2015 at 8:21
  • Can describe "this does not seem to be working" ? Commented Jun 12, 2015 at 8:23
  • Hi @adeneo, I tried replacing $(document).ready() with $(window).load() but to no avail. @guest271314: As in, it just isn't animating .init_leftbar by shifting it down by iHeight pixels. if I replace the first line with var iHeight = 100; however, this will animate by 100px... Commented Jun 12, 2015 at 8:30

4 Answers 4

1

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.

2
  • Thanks, as a complete newcomer to jquery and programming generally I didn't even know about the console in the browser. Doing this showed that the div #thing had a height of 0. I could work around this by pointing the selector at the image contained within the div, which gave me the value I was after. I don't know why it was returning zero? Perhaps something to do with its position being absolute? At any rate, found this useful, will have a play with outerheight() as well. Thanks! Commented Jun 12, 2015 at 8:47
  • .height() works with the div body, excluding padding margin and border, maybe that's you problem, or maybe the check is done before the image is loaded in the div. In that case you have to do it after the image is loaded in the div, you welcome! happy to help :)
    – Romeo
    Commented Jun 12, 2015 at 11:06
0

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();
1
  • How does this answer the question?
    – Zee
    Commented Jun 12, 2015 at 8:33
0

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

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.