Gregor Gregor - 3 months ago 8
Javascript Question

Unexpected behavior after running a custom jquery function

I do have a little bug in my Script which i do not know how to solve.

Everything here works as expected, but when i click

#backtop
and the Document is scrolled back to top and
display' : 'block
is set again.

May someone please explain how to prevent this.
Thanks a lot.

$(function () {

var didScroll;
var scrolled = 0;
var trigger = 900;

$(window).scroll(function () {
didScroll = true;
});

function hasScrolled() {
//store scroll position in var
var store = $(this).scrollTop();
if (scrolled < trigger) {
$('#backtop').css({'display': 'none'});
} else {
$('#backtop').css({'display': 'block'});
}
scrolled = store;
console.log('run')
}

setInterval(function () {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 1000);

$('#backtop').on('click', function (e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $('#sec-1').offset().top
}, 'slow');
$('#backtop').css({'display': 'none'});
});

});


EDIT:
the fiddle: https://jsfiddle.net/107qs76o/

Answer

You were assigning scrolled value after your calculation. It should be before calculation. i.e.

$(function() {

  var didScroll;
  var scrolled = 0;
  var trigger = 400;

  $(window).scroll(function() {
    didScroll = true;
  });

  function hasScrolled() {
    //store scroll position in var
    scrolled = $(this).scrollTop();
    if (scrolled < trigger) {
      $('#backtop').css({
        'display': 'none'
      });
    } else {
      $('#backtop').css({
        'display': 'block'
      });
    }
    // scrolled = store;
    console.log('run')
  }

  setInterval(function() {
    if (didScroll) {
      hasScrolled();
      didScroll = false;
    }
  }, 1000);

  $('#backtop').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $('#sec-1').offset().top
    }, 'slow', 'swing', function() {
      $('#backtop').css({
        'display': 'none'
      });
    });
  });

});
Comments