Search code examples
javascriptjqueryhtmlcssscroll

Detect scrolling after scrolling distance from current position in browser


I want to detect if i am scrolling but only after I've scrolled a certain distance from my current location. When I stop scrolling, this distance resets to the current location

I know how to detect scrolling past a certain point on the page with .scrollTop(), but I want this certain point to be my current location but only after I've stopped scrolling.

Why I need this: I have a navbar that changes all of it's css depending on if I've scrolled up or down. So if my scroll finger shivers in a different direction (from up to down scroll for example), the navbar will transform like a strobe light. So my plan was to only detect scrolls abover or below 10px so the user will need to make a dedicated scroll to activate the navbar css change.

pseudo code:

if (scrolled 10px above or below current_location in browser) {
  console.log('it worked');
} else {
  console.log('You have not scrolled far enough!')
}

if (scrolling stops) {
  reset position of current_location. 
}

Solution

  • This would be the simplest approach :

    $(document).ready(function() {
    
    var previous = 0;
    
    $(window).scroll(function() {
    
        var current = $(this).scrollTop();
    
        if (current > previous) // down
        else // up
    
        previous = current;
    });
    });
    

    http://codepen.io/anon/pen/ojxPOg?editors=001

    Using the mousewheel plugin, you'd know even before you've actually started scrolling what the direction is. Might be nice but for mobile the above would still be needed (for the quickest way).

    http://codepen.io/anon/pen/YPmjym?editors=001

    Edit - the first code might not work as expected on touch devices. Panning the screen doesn't actually fire a scroll until you release it (as far as I've experienced). Addressing that would need another script that will listen for touchmove events. Here's one example of how to do that :

    $(window).on('touchstart', function(e) {
    
        var swipe = e.originalEvent.touches,
        start = swipe[0].pageY;
    
        $(this).on('touchmove', function(e) {
    
            var contact = e.originalEvent.touches,
            end = contact[0].pageY,
            distance = end-start;
    
            if (distance < -30) // up
            if (distance > 30) // down
        })
        .one('touchend', function() {
    
            $(this).off('touchmove touchend');
        });
    });
    

    An amount of about 30 pixels is usually treated as a targeted swipe.