Abhinav
Abhinav

Reputation: 353

How to get offsetHeight, scrollHeight in AngularJS

I am creating a directive in which I need three values-

  1. scrollTop
  2. offsetHeight
  3. scrollHeight

    projectModule.directive('scroller', function ($window) {
    return {
    restrict: 'A',
    link: function (scope, elem, attrs) {
        var rawElement = angular.element($window);
        angular.element($window).bind('scroll', function () {
            var scrollTop = rawElement.scrollTop();
            var offsetHeight = rawElement.offsetHeight;
            var scrollHeight = rawElement.scrollHeight;
            console.log(scrollTop + " ," + offsetHeight + " ," + scrollHeight);
            scope.$apply();
            });
        };
    });
    

I can get scrollTop directly by using rawElement.scrollTop() function, but How to get offsetHeight and scrollHeight of that element?

I want to apply that logic-

if ((rawElement.scrollTop + rawElement.offsetHeight + 5) >= rawElement.scrollHeight) {
    scope.$apply();    //For infinite scrolling
}

Thanks in advance.

Upvotes: 2

Views: 9306

Answers (2)

dfsq
dfsq

Reputation: 193261

I would try to make use of $document service instead, since you actually need document.body.scrollHeight and document.body.offsetHeight. So

var offsetHeight = $document[0].body.offsetHeight;
var scrollHeight = $document[0].body.scrollHeight;

Upvotes: 3

captain_jim1
captain_jim1

Reputation: 1001

Can you use getBoundingClientRect if $el is the actual DOM element?

var top = $el.getBoundingClientRect().top;

JSFiddle

You could also try using

$el.prop('offsetTop')

Upvotes: 1

Related Questions