Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS 'scrollTop' equivalent?

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.

like image 796
pram Avatar asked Oct 11 '14 21:10

pram


People also ask

How to set scrollTop in AngularJS?

You can use $anchorScroll . Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

What is scrollTop()?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0.

Why is scrollTop not working?

If your CSS html element has the following overflow markup, scrollTop will not function. To allow scrollTop to scroll, modify your markup remove overflow markup from the html element and append to a body element. Hope this work!!


2 Answers

$window.pageYOffset

This is property from service $window

like image 74
Blaze Avatar answered Sep 26 '22 20:09

Blaze


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/

like image 22
HaukurHaf Avatar answered Sep 25 '22 20:09

HaukurHaf