rnk
rnk

Reputation: 2204

jquery - using .height()

I'm using jquery .height() to fetch the document height.

Please check this http://jsfiddle.net/rkumarnirmal/86q37/

After fetching the height, I'm placing the element in that position. Where you can see the document height is actually wrong, because it is going beyond the area.

How can I solve this?

Thanks!

Upvotes: 0

Views: 81

Answers (3)

Corbin
Corbin

Reputation: 33437

The top is relative to the top of #dummy.

So you need to subtract the height of #dummy from the height of the page:

$(function(){
    var h = $(document).height() - $("#dummy").height();
    $("#dummy").css("top", h+"px");
})​

I should mention though that you can do this in pure CSS:

http://jsfiddle.net/86q37/3/

If you're wanting to support old browsers though, you're going to either need to look up some CSS tricks to do it, or just stick with JS.

Upvotes: 3

David Thomas
David Thomas

Reputation: 253308

One solution is to use jQuery, and subtract the height of the element from the height of the body (and you don't need to worry about adding the px to the height, jQuery handles it internally):

$(function(){
    var h = $(document).height();
    $("#dummy").css("top", h - $('#dummy').height());
})​

JS Fiddle demo.

The easier solution is to simply use CSS:

#dummy {
    position: absolute;            
    width: 100px;
    height: 100px;
    bottom: 0; /* aligns the bottom of the element zero pixels from the bottom of the document */
    left: 0; /* aligns the left side of the element zero pixels from the left side of the document */
    background-color: red;
}​

JS Fiddle demo.

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

.height is returning the correct value. But you are setting top position of the box to be the height of the document. See below demo for better understanding,

$(function(){
    var h = $(document).height();
    $("#dummy").css("top", function () {
        return (h - $(this).height()) +"px"; 
      //This will place the box at top position subtracting 
      //the documentHeight - dummyHeight;
    });
})

DEMO

Upvotes: 1

Related Questions