1

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.

see my code

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

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

one small question without using jquery how can i achieve the same effect. would post any code where you will not use jquery. thanks for your great help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.