45

The wheel event in Firefox >= 17 has a deltaMode property. With the OS/mouse I'm using, it's set to 1 (or DOM_DELTA_LINE). This setting means that the deltaX and deltaY event values are measured in lines and not pixels. Sure enough, if I pretend the deltas are pixels, scroll speeds are much slower than they normally are in Firefox.

Chrome 31 by contrast uses a deltaMode of 0 (or DOM_DELTA_PIXEL), which allows me to simulate scrolling with normal speeds.

If I could convert the line values to pixel values, I'd be all set. But I can't find a scrap of documentation about what a "line" is. I tried changing the font-size and line-height in Firefox, which didn't change the scrolling behavior.

Anyone know how a "line" is defined? W3C just says, "This is the case for many form controls."

W3C deltaMode

MDN WheelEvent

MDN wheel

Edit: here's a fiddle to demonstrate the oddity. When Firefox is in DOM_DELTA_LINE mode, there's no consistent ratio between pixels and lines – it's all over the place. And when I switch to using a trackpad instead of a mouse, causing Firefox to switch to DOM_DELTA_PIXEL mode, there's also no consistent ratio. On the other hand, in Chrome 31, the ratio is almost always very close to 1:1 in DOM_DELTA_PIXEL mode.

Chromium issue: implement DOM3 wheel event

Bugzilla bug: implement DOM3 wheel event

Update: Scrolling by single ticks of a mouse wheel in Firefox where deltaMode is DOM_DELTA_LINE, the pixel delta is dependent on the CSS font-size, but not on line-height. See this fiddle for a demonstration. This behavior only holds when ticking the wheel very slowly. With speed or momentum, the line to pixel ratio isn't predictable at any particular instance or in aggregate. As far as I can tell, there's no way to emulate Firefox's scroll behavior using the delta measurements provided in DOM_DELTA_LINE mode.

In DOM_DELTA_PIXEL mode, the behavior is nearly pixel-perfect. That is, the ratio between actual pixels scrolled and the reported pixel delta value is almost exactly 1, which is demonstrated in the the same fiddle.

I filed a bug with Mozilla, arguing that the behavior of the wheel event in DOM_DELTA_LINE mode isn't useful because it isn't predictable (i.e., it's an equation where both the unit and the magnitude are variables). The issue has been marked invalid because the expected behavior is for the wheel event to pass through the native deltas provided by the OS, despite the fact that Firefox itself doesn't honor these deltas.

I'll leave this question open in the hope that DOM_DELTA_LINE will be defined by a spec somewhere. As far as I know, the dependence on font-size (and not line-height) isn't yet described anywhere.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JKS
  • 3,710
  • 2
  • 29
  • 40
  • 2
    See this related answer here which suggests using some code from Facebook which uses LINE_HEIGHT = 40 and PAGE_HEIGHT = 800 http://stackoverflow.com/a/30134826/4387229. There's also a ready to use npm package of this code extract. See here for more details https://www.npmjs.com/package/normalize-wheel – Simon Watson Oct 29 '16 at 11:23

5 Answers5

26

Overview:

While the scroll value resulting from DOM_DELTA_LINE may not be specifically defined by any specification, based on the following comment from the Chromium issue tracker and my own observations, it appears that Firefox is presently the only browser that will report wheel events with anything other than deltaMode as DOM_DELTA_PIXEL (0).

Comment from Chromium issue Implement DOM3 wheel event:

We ended up doing what IE does and report the exact number of pixels we would scroll the element.

The following asserts are always true (given that the element can be scrolled).

element.scrollTop = 0;
element.addEventListener('wheel', function(e) {
  assert(e.deltaMode === MouseEvent. DOM_DELTA_PIXEL);
  assert(element.scrollTop === e.deltaY);
});
// scroll

This way you know exactly how much to scroll at all times.

We never set the deltaMode to anything else but DOM_DELTA_PIXEL.

According to that comment, Chromium matches IE's only-pixel deltas. Though not covered, this almost certainly extends directly to modern Opera and Safari. My own observations from testing on Window, Mac, and Linux with multiple input devices did not disprove this.

So since Firefox is the only browser that will report a deltaMode of DOM_DELTA_LINE (1) or DOM_DELTA_PAGE (2), for the time being anyway, we only need to know what Firefox computes these values as. Well, that's where things get a bit tricky, but through searching through the Firefox source and some trial and error, I've determined it directly corresponds the default font and default font-size. Specifically those configured in the following preferences, ignoring any CSS on the page.

Firefox fonts preferences options

That means that to correctly detect the line-height used in scrolling, you must have a completely un-styled inline element to detect the computed rendering height from. Since CSS on the page will almost certainly interfere, we must create a new and clean window in an iframe to do the detection.

Detecting the line-height used by DOM_DELTA_LINE triggered scroll events:

For this purpose, I have created the following little function to synchronously detect the pure, unaltered line-height.

function getScrollLineHeight() {
    var r;
    var iframe = document.createElement('iframe');
    iframe.src = '#';
    document.body.appendChild(iframe);
    var iwin = iframe.contentWindow;
    var idoc = iwin.document;
    idoc.open();
    idoc.write('<!DOCTYPE html><html><head></head><body><span>a</span></body></html>');
    idoc.close();
    var span = idoc.body.firstElementChild;
    r = span.offsetHeight;
    document.body.removeChild(iframe);
    return r;
}

// Get the native croll line height.
console.log(getScrollLineHeight());

Ok, so now we know just how much a line-height delta should translate to in pixels. However, on Window, there is one other thing that you may need to take into consideration. On Windows, the default scroll speed is overridden to make it 2x faster by default, but only for the root element.

Override system of system scroll speed:

We're providing an override mechanism of system scroll speed because the default system scrolling speed of Windows is slower than WebKit's scrolling speed. This was suggested for alternative way of the acceleration system (see next section).

This is enabled in default settings only on Windows. mousewheel.system_scroll_override_on_root_content.enabled can switch it.

On Windows, only when the system scroll speed settings are not customized by user or mouse driver, this overrides the scrolling speed. On the others, this always overrides the speed.

The ratio can be specified by hidden prefs. mousewheel.system_scroll_override_on_root_content.vertical.factor is for vertical scrolling event. mousewheel.system_scroll_override_on_root_content.horizontal.factor is for horizontal scrolling event. The values are used as 1/100 (i.e., the default value 200 means 2.0).

nsEventStateManager multiplies the scrolling speed by the ratio when it executes to scroll a root scrollable view of a document. So, DOMMouseScroll event's delta value has never been overwritten by this.

See also bug 513817.

This is only applicable by default to the root of the document, scrolling elements within the document like a textarea are not affected (except maybe iframes?). There's also no way to get the specified value if the default 2x is reconfigured, so if you deem this value important, you will have to resort to user-agent OS sniffing, perhaps with the technically non-standard yet popular navigator.platform.

What about DOM_DELTA_PAGE?:

Windows also has an alternate setting for vertical scrolling where instead of scrolling by the number of lines, it scroll by an almost full page. To clarify, this is the dialog with the "One screen at a time" setting controlling this in Windows 7.

Windows 7 wheel settings

When this is activated, a single click will scroll almost a full page, here meaning the height of the scrolling panel, minus the scroll bars. I say almost, because Firefox takes some other things into consideration to reduce the amount of scrolling. Namely, reducing by some lines, a percentage, and somehow subtracting the fixed position headers and footers. See the following block of code for some of the logic.

Excerpt from layout/generic/nsGfxScrollFrame.cpp:

nsSize
ScrollFrameHelper::GetPageScrollAmount() const
{
  nsSize lineScrollAmount = GetLineScrollAmount();
  nsSize effectiveScrollPortSize;
  if (mIsRoot) {
    // Reduce effective scrollport height by the height of any fixed-pos
    // headers or footers
    nsIFrame* root = mOuter->PresContext()->PresShell()->GetRootFrame();
    effectiveScrollPortSize =
      GetScrollPortSizeExcludingHeadersAndFooters(root, mScrollPort);
  } else {
    effectiveScrollPortSize = mScrollPort.Size();
  }
  // The page increment is the size of the page, minus the smaller of
  // 10% of the size or 2 lines.
  return nsSize(
    effectiveScrollPortSize.width -
      std::min(effectiveScrollPortSize.width/10, 2*lineScrollAmount.width),
    effectiveScrollPortSize.height -
      std::min(effectiveScrollPortSize.height/10, 2*lineScrollAmount.height));
}

I'm not 100% sure what exactly is detected as a fixed position header and footer element and what isn't, but this should give a pretty good overview of how the DOM_DELTA_PAGE mode also works, in addition to the DOM_DELTA_LINE which this question asks about.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
4

I tried your fiddle with Firefox 25 (on Linux) - and extended it for tracking scrollTop only on wheel events. In your fiddle, the scrolling delta is calculated in the scroll event which is triggered much more often than the wheel event. Also, scrolling events in soft scrolling mode seem to lag behind compared to wheel events. (I.e. if you measure while soft scrolling has not finished yet then you get "intermediate" values for scrollTop().) I think that these are the reasons why you do not get good correlation between scroll delta and wheel events. (Note: The wheel event seems to be handled before associated scroll events.)

If soft scrolling is switched off then there is at least one wheel event per scroll event. Your fiddle gives a perfectly constant "px/DOM_DELTA_LINE: 18" during "wheeling" for me. If I add a div with two spans <span id="lineN">N</span> and a <br/> between and measure ($("#line2").position().top - $("#line1").position().top) then I get exactly 18.

Summary: The wheel event allows to calculate the scroll distance in pixels - at least in my environment. I hope this is true for yours too.

Here is the JavaScript code of my extended fiddle for your fiddle with my extensions:

var DeltaModes = {
    0: "DOM_DELTA_PIXEL",
    1: "DOM_DELTA_LINE",
    2: "DOM_DELTA_PAGE"
};
var statsPane = $(".stats-pane");
var scrollTop = $(window).scrollTop();
var scrollDelta = 0;
var wheelEvents = 0;
var scrollEvents = 0;
var scrollTopOnWheel = 0;
$(window).scroll(function(){
    scrollEvents++;
    var newScrollTop = $(window).scrollTop();
    scrollDelta = scrollTop - newScrollTop;
    scrollTop = newScrollTop;
});
$(window).on("wheel", function(e){
    wheelEvents++;
    var wheelScrollTop = $(window).scrollTop();
    var wheelScrollDelta = wheelScrollTop - scrollTopOnWheel;
    e = e.originalEvent;
    var pxPerDeltaUnit = Math.abs(scrollDelta) / Math.abs(e.deltaY);
    var deltaMode = DeltaModes[e.deltaMode];
    var stats = [deltaMode + ": " + e.deltaY];
    stats.push("px delta: " + scrollDelta);
    stats.push("px/" + deltaMode + ": " + pxPerDeltaUnit);
    stats.push("wheel scroll top (prev): " + scrollTopOnWheel);
    stats.push("wheel scroll top: " + wheelScrollTop);
    stats.push("wheel scroll delta: " + wheelScrollDelta);
    stats.push("line height: " + ($("#line2").position().top - $("#line1").position().top));
    stats.push("wheel event#: " + wheelEvents);
    stats.push("scroll event#: " + scrollEvents);
    statsPane.html('<div>' + stats.join('</div><div>') + '</div>');
    scrollTopOnWheel = wheelScrollTop;
    //scrollTop = newScrollTop;
});

And the HTML:

<div class="stats-pane"></div>
<div>Hey.</div>
<div>Hi.</div>
<div>Hello.</div>
<div>
    <span id="line1">1</span><br/>
    <span id="line2">2</span><br/>
</div>
halfbit
  • 3,414
  • 1
  • 20
  • 26
  • Interesting… I moved the `scrollTop` calculation to the `wheel` event callback, and removed the `scroll` listener altogether. On a Mac, on Firefox 25, I still get a widely varying px/DOM_DELTA_LINE value. Scrolling on my mouse one tick at a time, I typically get values around 10px, 20px, and 30px. Even with smooth scrolling disabled, I still get widely varying values. http://jsfiddle.net/neonsilk/Zd7yB/3/ – JKS Nov 25 '13 at 19:01
  • Strange. But no Mac here to investigate, sorry. You may want to have a look at [Gecko:Mouse Wheel Scrolling](https://wiki.mozilla.org/Gecko:Mouse_Wheel_Scrolling). It contains infos about mouse wheel related features (e.g. "acceleration system") and configuration settings. – halfbit Nov 25 '13 at 20:22
3

There's now a slightly simpler way to get the scroll line height (browser's default font-size) without using iframes by using font-size: initial.

function getScrollLineHeight() {
  const el = document.createElement('div');
  el.style.fontSize = 'initial';
  el.style.display = 'none';
  document.body.appendChild(el);
  const fontSize = window.getComputedStyle(el).fontSize;
  document.body.removeChild(el);
  return fontSize ? window.parseInt(fontSize) : undefined;
}

// Get the native scroll line height
console.log(getScrollLineHeight());

I tested this on latest versions of Chrome, Firefox, Safari (tested 9 and 12), Edge and IE11 on a page which overrides the font-size of html and body elements. This seems to work reliably on all other tested browsers except on IE11. On IE11 it will return the inherited font-size from body since IE11 doesn't support the CSS keyword initial.

So if you don't need to support IE11 anymore, this should work.

Haprog
  • 793
  • 1
  • 9
  • 21
  • 1
    Thanks. In my opinion (and for my use case) this is totally sufficient. Since IE 11 uses `DOM_DELTA_PIXEL` anyway, this isn't a show stopper when still needing to support IE 11. – alex3683 Mar 09 '20 at 08:48
-3

I haven't looked at your code, but this is how I solved my problem, which led me here.

You can try to override browser's scroll with your custom one.

window.addEventListener("wheel", function(e){
 if(e.deltaY > 0)
   window.scroll(0,20);
 else
   window.scroll(0,-20)

 e.preventDefault();
});

This way you will be always sure about the amount of pixels scrolled.

  • I don't understand all the downvotes, this answer actually brought me on the right track: With the wheel in most cases the delta doesn't really matter, except the sign of it. – Martin Cremer Aug 15 '19 at 19:13
  • While this might have been enough for a classic mouse wheel, it doesn't work correctly when using touchpad (or trackpoint) scrolling, non-discrete (hi-res) mouse wheels, etc. These devices generate a lot more events and thus each event should only scroll a little bit (that's what the delta is for...) – Ghost4Man May 01 '23 at 14:07
-6

I found that using the following snippet resolve the problem. It normalizes the deltaX and deltaY. Try this one.

function onWheel(e) {
    var deltaX = Math.max(-1, Math.min(1, (e.deltaX)));
    var deltaY = Math.max(-1, Math.min(1, (e.deltaY)));
    console.log('deltaX: ' + deltaX + ', deltaY: ' + deltaY);
}

Where e is WheelEvent object.

Bogie
  • 153
  • 9