Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect scroll speed with Jquery?

I would like to try and replicate io7's safari feature, where the url and navigation bars minimize when you scroll slowly, in javascript/jquery. The first thing is to detect scroll speed, I have seen this question already, but I am doing this in a content script so I don't necessarily have the top and bottom element that they use. Is there another way to detect scroll speed?

like image 994
EasilyBaffled Avatar asked Feb 09 '14 14:02

EasilyBaffled


2 Answers

You could attach to the scroll event via jQuery and use a combination of timestamps and the scrollOffset to determine scroll speed by comparing the offset/time to the last scroll event before. Something like this:

var lastOffset = $( mySelector ).scrollTop();
var lastDate = new Date().getTime();

$( mySelector ).scroll(function(e) {
    var delayInMs = e.timeStamp - lastDate;
    var offset = e.target.scrollTop - lastOffset;
    var speedInpxPerMs = offset / delayInMs;
    console.log(speedInpxPerMs);

    lastDate = e.timeStamp;
    lastOffset = e.target.scrollTop;
});

Anyways since you don't have control over navigation bar in a regular browsers I don't see the point here :/

May be you are searching for something like this: Parallax scroll with sticky header

GL Chris

like image 98
cschuff Avatar answered Oct 13 '22 19:10

cschuff


I tried to use cschuffs answer but something was wrong. With this problem and the joy to write a class, I just put the code in a small class, get it here: https://github.com/SocialbitGmbH/JavascriptScrollSpeedMonitor

Usage is simple:

var scrollSpeedMonitor = new ScrollSpeedMonitor(function (speedInPxPerMs, timeStamp, newDirection)
{
    console.log('Scroll speed: ' + speedInPxPerMs);
});
like image 23
Thomas Kekeisen Avatar answered Oct 13 '22 19:10

Thomas Kekeisen