3

I'm trying to prevent default scrolling behavior while still determining the number of pixels a user has attempted to scroll.

My objective is (at some vertical position on my page) to fix a navigation element to the top of the screen and hijack the scroll/swipe event to pull down a mobile menu when the user scrolls back up (so moving said element up and down by n pixels depending on how many pixels the user tries to scroll).

I am aware of the UX/accessibility concerns insofar as blocking native behavior, but the suits want what the suits want.

So far I have:

$('body').on({
 'mousewheel' : function(e) {
    e.preventDefault(); 
    e.stopPropagation();
 }
}); 

but am stumped as to how to access the number of pixels scrolled (since element/scroll offsets are no longer a guide).

Edit: Please note that this question is specifically asking for information regarding mouse/scroll actions while scrolling is blocked. Don't think this has been appropriately marked as duplicate.

Delon
  • 255
  • 3
  • 21
  • possible duplicate of [How to disable scrolling temporarily?](http://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily) – suvroc Jun 19 '15 at 12:12
  • use jquery swipe event – Frane Poljak Jun 19 '15 at 12:15
  • 2
    @suvroc I don't think it's a duplicate, that post doesn't provide any information about capturing scrolled pixels while scrolling is disabled. – Delon Jun 19 '15 at 12:16
  • need an example... why not just move on each `mousewheel` for some pixels? its fired for each scroll step. should be fine. – befzz Jun 19 '15 at 12:44
  • @befzz if you know how to do that, please provide an answer. I know how to track the movement of the body, but if I'm cancelling the propagation of mousewheel (to stop the page from scrolling) I have no idea how to get the information about how many pixels the user has scrolled. – Delon Jun 22 '15 at 07:27

2 Answers2

5

This is browser-depended because of the mousewheel event you are using. This is because it is non-standard. Don't use it!

In Chrome (43.0) you get different properties with different values:

e.originalEvent.wheelDelta: -120
e.originalEvent.wheelDeltaY: -120
e.originalEvent.deltaY: 100

In IE (11.0), you can get only one property:

e.originalEvent.wheelDelta: -120

In Firefox (38.0.5), the capturing of the mousewheel event doesn't work at all.

Solution:
Use the wheel event (MDN reference). This event has the e.originalEvent.deltaY property in all browsers.

Raidri
  • 17,258
  • 9
  • 62
  • 65
2

Before cancelling event propagation take the deltaY out of the original event like this

$('body').on({
  'wheel' : function(e) {
      console.log(e.originalEvent.deltaY);
      e.preventDefault(); 
      e.stopPropagation();
 }
}); 
Moti Korets
  • 3,738
  • 2
  • 26
  • 35