Reputation: 642
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.
Upvotes: 17
Views: 54765
Reputation: 1075
You can use
angular.element(document).bind('scroll', function() {
if (window.scrollTop() > 100) {
$this.fadeIn();
} else {
$this.fadeOut();
}
});
Upvotes: 0
Reputation: 1
You can use like as polyfill here a link
function offset(elm) {
try {return elm.offset();} catch(e) {}
var rawDom = elm[0];
var _x = 0;
var _y = 0;
var body = document.documentElement || document.body;
var scrollX = window.pageXOffset || body.scrollLeft;
var scrollY = window.pageYOffset || body.scrollTop;
_x = rawDom.getBoundingClientRect().left + scrollX;
_y = rawDom.getBoundingClientRect().top + scrollY;
return { left: _x, top: _y };
}
Upvotes: 0
Reputation: 13740
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
Upvotes: 3
Reputation: 13816
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/
Upvotes: 4