Get scroll wheel amount in jQuery
Asked Answered
C

2

8

After binding the scroll event to an object, how can I get the amount the user scrolled by?

$(selector).scroll(function(e) {
    // get scroll amount
});

Firefox and Opera have the property detail whereas IE, Safari, and Opera have wheelData. To make matters worse, Firefox and Opera operate on a scale of -3 to 3, and IE and Safari go from -120 to 120.

Is there a single, normalized property that jQuery provides for this?

Colleen answered 22/6, 2012 at 15:4 Comment(0)
R
10

Use jQuery .scrollTop() and save the value between scroll events, then get the delta at next scroll event.

var old_scroll_top = 0;

$(document).scroll(function() {
  var current_scroll_top = $(document).scrollTop();
  var scroll_delta = current_scroll_top - old_scroll_top;

  // do something with current_scroll_top and scroll_delta

  old_scroll_top = current_scroll_top;
});

Example: jsFiddle


Update:

Here is a second Example, which shows how to have a canvas, that updates according to scoll Events.

Radioactivity answered 22/6, 2012 at 15:7 Comment(4)
+1 for the idea and example. Unfortunately I'm trying to do this in a <canvas>, which is not scrollable.Colleen
how about overlaying the <canvas> with a invisible <div> and suppressing the scroll bar. then of course you would have to pass on all click events to the canvas. so it depends on the intention you have for the canvas. you would make sure the canvas does not move by setting it's css position attribute to fixed.Radioactivity
even better: how about placeing the canvas on a really big page and setting it's css position attribute to fixed.Radioactivity
i added an update, with an example of a canvas, that reacts on scroll events. if you want to hide the scroll bar , just use overflow:hidden.Radioactivity
L
0

Could you use scrollTop for this?

var amount = $(window).scrollTop();
Lippi answered 22/6, 2012 at 15:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.