Reputation: 2451
many web site has feature for long page like when user scroll down bit then a arrow sign comes at right side and when user click on that arrow then pages scroll to top. i try to do the same with custom directive. my code is working but there is one issue that when programmatically page is scrolling upward then some time arrow sign is getting visible and invisible which looks bad. so my request please some one see my code in jsfiddle and suggest me what is wrong there which causes arrow sign getting visible and invisible.
here is my jsfiddle https://jsfiddle.net/tridip/hzgjcojg/2/
i have mixed bit jquery because i did not know how to achieve purely it by java script and jquery is very easy for having smooth effect with animate function.
please see my code and give your suggestion why some time arrow sign is getting visible and invisible during page scroll upward.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [];
for (var i=0; i<100; i++) { $scope.items.push(i); }
});
app.directive('scrollOnClick', function() {
return {
restrict: 'EA',
template:'<a title="Click here to go top" class="scrollup" href="#" >Scroll</a>',
link: function(scope, $elm) {
$(window).scroll(function () {
if ($(this).scrollTop() > 300) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
});
$elm.on('click', function() {
//alert('hello');
$("html,body").animate({scrollTop: 0}, "slow");
});
}
}
});
thanks
Upvotes: 1
Views: 2384
Reputation: 6253
It's because you are using an <a>
tag with href="#"
as your template in your directive. It shows the window scroll position as 0
for the first instance if you log the $(this).scrollTop()
in the $(window).scroll
function which leads to the fade animation to start fading out and right after fade in again. One way to make it work is to replace the template with a div or something else OR removing the href
from the template.
Fiddle: https://jsfiddle.net/tmdy51rh/3/
EDIT:
Without jQuery you could do something like this:
Fiddle: https://jsfiddle.net/tmdy51rh/5/
Upvotes: 2