AngularJS 'scrollTop' equivalent?

53,945

Solution 1

$window.pageYOffset

This is property from service $window

Solution 2

I don't believe there's anything in Angular to get the scroll position. Just use plain vanilla JS.

You can retrieve the scrollTop property on any element.

https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

document.body.scrollTop

Fiddle for you: http://jsfiddle.net/cdwgsbq5/

Solution 3

Inject the $window into your controller and you can get the scroll position on scroll

var windowEl = angular.element($window);
var handler = function() {
    console.log(windowEl.scrollTop())
}
windowEl.on('scroll', handler);

Fiddle

Adaptation from another stackoverflow answer

Share:
53,945
pram
Author by

pram

I like go and go accessories

Updated on July 16, 2022

Comments

  • pram
    pram almost 2 years

    I'm looking to implement something similar to this in an AngularJS directive:

    https://github.com/geniuscarrier/scrollToTop/blob/master/jquery.scrollToTop.js

    It's fairly straightforward, when you are not at the top of the page it will fade in a button to scroll to the top:

    $(window).scroll(function() {
      if ($(this).scrollTop() > 100) {
        $this.fadeIn();
      } else {
        $this.fadeOut();
      }
    });
    

    However I'm having a hard time finding how to get the current scroll location in Angular. I'd rather not have to use jQuery just for this single thing.

  • Jarno van Rhijn
    Jarno van Rhijn over 9 years
    This results in different behavior in chrome and firefox. Any solution for this issue?
  • pcnate
    pcnate about 9 years
    I would guess that this is accessing the jqLite ( or jQuery ) method?
  • Shankar ARUL
    Shankar ARUL about 9 years
    yep with Angular's jqlite !
  • ishmaelMakitla
    ishmaelMakitla about 8 years
    You should really add some explanation as to why this code should work - you can also add comments in the code itself - in its current form, it does not provide any explanation which can help the rest of the community to understand what you did to solve/answer the question.