Reputation: 22747
This is my current directive, which I found as the second answer to the following question - ScrollTo function in AngularJS:
.directive('scrollToItem', function($timeout) {
return {
restrict: 'A',
scope: {
scrollTo: "@"
},
link: function(scope, $elm,attr) {
$elm.on('click', function() {
$('html,body').animate({scrollTop: $(scope.scrollTo).offset().top }, "slow");
});
}
}})
The code above can be used like so:
<a id="top-scroll" name="top"></a>
<div class="back-to-top" scroll-to-item scroll-to="#top-scroll">
The issue is that this causes the page to quickly scroll all the way up and then animate from the top. Is there a recommended way for me to scroll from the current location to the desired position?
Upvotes: 0
Views: 635
Reputation: 22747
One solution would be to change
$elm.on('click', function() {
$('html,body').animate({scrollTop: $(scope.scrollTo).offset().top }, "slow");
});
to
$elm.on('click', function(e) {
e.preventDefault();
$('html,body').animate({scrollTop: $(scope.scrollTo).offset().top }, "slow");
});
which I found here: jQuery flicker when using animate-scrollTo
I'll wait and see if there is a better solution. If not, I'll just mark this one as the correct solution.
Upvotes: 1