0

I am trying to determine if the user has scrolled up or down and I found some code in a different answer that seems to help me out. My one problem with this code is that I cannot wrap my head around how to capture last_scroll_position. I have a function set up to that returns scrollTop so getting the value for the variable current_position is not a problem, but getting the value for last_scroll_position seems a bit tricky.

Here is the answer I found...

Keep a variable, say, last_scroll_position, and when you have a scroll, if last_scroll_position - current_position > 0, the user scrolled up, and down if it's less than 0.

Differentiate between scroll up/down in jquery?

Community
  • 1
  • 1
tripstar
  • 161
  • 1
  • 2
  • 11

1 Answers1

0

I recommend that check out this example: stackoverflow.com/a/24815216...

The scroll event behaves oddly in Firefox, it is fired a lot of times because of the smoothness scrolling, but it works, here are an example:

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "35px",
    left: "35px" });

//binds the "scroll" event
$(window).scroll(function (e) {
    var target = e.currentTarget,
        scrollTop = target.scrollTop || window.pageYOffset,
        scrollHeight = target.scrollHeight || document.body.scrollHeight,
        lastScrollTop = $(target).data("lastScrollTop") || 0,
        scrollText = "";

    if (scrollTop > lastScrollTop) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }
    $("#test").html(scrollText +
      "<br>scrollTop: " + scrollTop +
      "<br>lastScrollTop: " + lastScrollTop);

    if (scrollHeight - scrollTop === $(target).innerHeight()) {
      console.log("► End of scroll");
    }
    //saves the current scrollTop
    $(target).data("lastScrollTop", scrollTop);
});
Community
  • 1
  • 1
jherax
  • 5,238
  • 5
  • 38
  • 50