I'm having some trouble understanding how to get the scroll position of window within my controller, so I can build logic around it.
From all the questions and answers I've been reading the most accepted answer seems to be to write a directive that calculates the scroll position, stick that directive on an element, and that's it.
However, when you want to do something along the lines of:
if (scrollY > 100 ){
$scope.showMenu = true;
}
if (scrollY > 500) {
$scope.showFooter = true;
}
This approach doesn't seem to work, because the calculated position in the directive can't be accessed from the controller. What would be the right 'Angular' way of doing this, which would still allow slightly more complicated logic to be executed from the controller?
How can I get the scrollbar position? To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.
According to @RobKohr comment, here's a optimized approach using .on('scroll')
and $scope.$apply
to update a scope element on scroll.
$document.on('scroll', function() {
// do your things like logging the Y-axis
console.log($window.scrollY);
// or pass this to the scope
$scope.$apply(function() {
$scope.pixelsScrolled = $window.scrollY;
})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With