Reading the AngularJS docs I haven't figured out if $anchorScroll
can have a duration/easing option to smooth scroll to elements.
It only says:
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
I do not use jquery and don't want to; is there still a clever yet simple way to make or extend $anchorScroll
in order to make scrolling more smooth?
Alan, thank you. If anyone interested, I formatted it based on John Pappa standards.
You can also use ngSmoothScroll, link: https://github.com/d-oliveros/ngSmoothScroll.
Just include the
smoothScroll
module as a dependency and use it like this:<a href="#" scroll-to="my-element-3">Click me!</a>
The answer from Brett worked great for me. I did some small changes on his solution in terms of modularization and testability.
Here's is yet another working example on JsFiddle that includes the other version with testing included.
For testing, I'm using Karma and Jasmine. Signature has been slightly modified as follows:
Where element is a mandatory attribute to scroll to and speed is optional where the default is 20 (as it was before).
None of the solutions here actually does what OP originally asked, that is, make
$anchorScroll
scrolling smoothly. Difference between smooth scrolling directives and$anchroScroll
is that it uses/modifies$location.hash()
, which may be desirable in some cases.Here is gist for simple module that replaces $anchorScroll scrolling with smooth scrolling. It uses https://github.com/oblador/angular-scroll library for the scrolling itself (replace it with something else if you want, it should be easy).
https://gist.github.com/mdvorak/fc8b531d3e082f3fdaa9
Note: It actually does not get $anchorScroll to scroll smoothly, but it replaces its handler for scrolling.
Enable it simply by referencing
mdvorakSmoothScroll
module in your application.You can also use the angular-scroll, link "https://github.com/durated/angular-scroll/". It is smooth scrolling also few easing functions to get a professional look.
I am not aware of how to animate
$anchorScroll
. Here's how I do it in my projects:And the JS function: