Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JavaScript: Detecting scroll direction - code structure issue

I need to detect the direction in that a user scrolls - "up" or "down". Based on the code found in this answer: How can I determine the direction of a jQuery scroll event?

I tried to wrap it in a function so it's a bit more differentiated - but unfortunately, it's not working. I think it has something to do with how I return the value, but the direction is always "up". Being fairly new to JavaScript I am having problems solving this issue.

Here is the code:

$(document).ready(function () {

    'use strict';

    var lastScrollTop = 0,
        st,
        direction;

    function detectDirection() {

        st = window.pageYOffset;

        if (st > lastScrollTop) {
            direction = "down";
        } else {
            direction = "up";
        }

        lastScrollTop = st;

        return  direction;

    }

    $(window).bind('scroll', function() {

        detectDirection();
        console.log(detectDirection());

    });

});

And I've also set up a Fiddle.

Could you please help me spotting where the problem is?

like image 292
Sven Avatar asked Mar 07 '13 06:03

Sven


People also ask

How can I determine the direction of jQuery scroll event?

Parameters: This method accepts single parameter position which is optional. It is used to specify the vertical scrollbar position in pixels. Return Value: It returns the vertical position of the scrollbar of selected element.

How do you know if scroll is up or down?

When the page scroll happens, compare the previous scrollY value with the current scrollY . If the current value is greater than the old value, then the scroll direction is downwards. Otherwise, the scroll direction is upwards. Update the current scroll position to the variable.

How do I check if JavaScript is scrolling?

this works: window. onscroll = function (e) { // called when the window is scrolled. }

How can I tell if someone is scrolling down?

If you want to check whether the user has scrolled to the bottom of the page, you can use the scroll() jQuery event. The given code piece takes the top scroll of the window, so how much the page is scrolled down, it adds the height of the visible window and checks if it is equivalent to the height of the document.


1 Answers

I'm providing a new answer because while BarMar's answer solves your immediate problem, the solution doesn't help you structure the code in a way that will enable you to do two things.

  1. Scope the scroll object more broadly, allowing you to access its attributes elsewhere. This would allow you to do something if the scroll position is a certain value.

  2. Improve the performance of the scrolling.

    // Your current functionality
    $(document).ready(function() {
      var scroll = {
        down: true,
        pos: 0
      };
      var scrollPos;
    
      var detectDirection = function() {
        scrollPos = window.pageYOffset;
    
        if (scrollPos > scroll.pos) {
          scroll.down = true;
        } else {
          scroll.down = false;
        }
    
        scroll.pos = scrollPos;
      };
    
      $(window).on('optimizedScroll', function() {
        detectDirection();
    
        // Do something based on scroll direction
        if (scroll.down == true) {
          // fooFunction();
        } else {
          // barFunction();
        }
    
        // Do something based on scroll position,
        // where scrollTrigger is a number
        if (scroll.pos > scrollTrigger) {
          // bazFunction();
        }
      });
    });
    
    // Improve scroll performance
    (function() {
        var throttle = function(type, name, obj) {
          var obj = obj || window;
          var running = false;
          var func = function() {
            if (running) {
              return;
            }
            running = true;
            requestAnimationFrame(function() {
            obj.dispatchEvent(new CustomEvent(name));
              running = false;
            });
          };
          obj.addEventListener(type, func);
        };
    
        throttle('scroll', 'optimizedScroll');
    })();
    

Rather than using .bind(), you should use .on(), as per the jQuery .bind() documentation.

The Immediately Invoked Function Expression (IIFE) to improve the scroll performance comes from the MDN documentation for the scroll event.

like image 193
SwankyLegg Avatar answered Oct 12 '22 05:10

SwankyLegg