Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollheight of an element gives undefined value

In an element I've given CSS overflow: scroll;. Now in jQuery I want to have it's original height (containing all child elements' height). Children under this element are dynamically changing. I want to have height on scroll event. Here is the code:

$("#container").scroll(function(e) {
    scrollAll();
});

function scrollAll(){
    var elemHeight = $("#container").scrollHeight;
    var scrollHeight = $("#scrollbars").scrollHeight;
    var ratio = elemHeight / scrollHeight;

    $("#outup").html( elemHeight +" and "+ scrollHeight +" ratio "+ ratio +" = "+ ($("#container").scrollTop()));
}

Issue: It throws scrollHeight is undefined error. What's wrong?

like image 740
Parag Gajjar Avatar asked Feb 22 '12 09:02

Parag Gajjar


People also ask

Why is scrollHeight undefined?

The "Cannot read property 'scrollHeight' of undefined" error occurs when the scrollHeight property is accessed on an undefined value, e.g. array index out of bounds. To solve the error, make sure to only access the scrollHeight property on valid HTML elements.

What is the difference between scrollHeight and clientHeight?

clientHeight: It returns the height of an HTML element including padding in pixels but does not include margin, border and scrollbar height. scrollHeight: It returns the height of the content enclosed in an html element including padding but not margin, border and scroll bar.

What is the scrollHeight?

The scroll height refers to the entire height of that element in the HTML page, even if it is not viewable due to overflow property. The element's scroll height includes the height assigned in CSS property plus the padding, but it does not include the margin, border, or scrollbar.

How do you get scrollHeight?

To get the height of the scroll bar the offsetHeight of div is subtracted from the clientHeight of div. OffsetHeight = Height of an element + Scrollbar Height. ClientHeight = Height of an element. Height of scrollbar = offsetHeight – clientHeight.


2 Answers

There is no scrollHeight in jQuery - it's scrollTop():

var elemHeight = $("#container").scrollTop();
var scrollHeight = $("#scrollbars").scrollTop();

Alternatively if you want to use the native scrollHeight property, you need to access the DOM element in the jQuery object directly, like this:

var elemHeight = $("#container")[0].scrollHeight;
var scrollHeight = $("#scrollbars")[0].scrollHeight;

Or like this:

var elemHeight = $("#container").prop('scrollHeight');
var scrollHeight = $("#scrollbars").prop('scrollHeight');
like image 157
Rory McCrossan Avatar answered Oct 07 '22 01:10

Rory McCrossan


If you are using Jquery 1.6 or above, use prop to access the value.

$("#container").prop('scrollHeight')

Previous versions used to get the value from attr but not post 1.6.

like image 24
Ankit Avatar answered Oct 07 '22 00:10

Ankit