AngularJS 'scrollTop' equivalent?
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);
Adaptation from another stackoverflow answer
![pram](https://i.stack.imgur.com/o8Fh4.png?s=256&g=1)
Comments
-
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 over 9 yearsThis results in different behavior in chrome and firefox. Any solution for this issue?
-
pcnate about 9 yearsI would guess that this is accessing the jqLite ( or jQuery ) method?
-
Shankar ARUL about 9 yearsyep with Angular's jqlite !
-
ishmaelMakitla about 8 yearsYou 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.