6

I'm trying to catch whether the mousewheel is triggered and whether it's scrolled up or down without actually scrolling the page (body has an overflow: hidden).

Any idea's how I can achieve this using jQuery or pure javascript?

$(window).scroll(function(){
    if( /* scroll up */){ }
    else { /* scroll down */ }
});
Enzio Rossa
  • 125
  • 1
  • 1
  • 11

2 Answers2

6

I rarely promote plugins but this one is just excellent (and relatively small in size) :

https://plugins.jquery.com/mousewheel/

It'll allow to do something like this :

$(window).mousewheel(function(turn, delta) {

  if (delta == 1) // going up
  else // going down

  // all kinds of code

  return false;
});

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


Update - at this point the mousewheel plugin could be replaced with the wheel event if legacy browsers need not be supported:

$(window).on('wheel', function(e) {

  var delta = e.originalEvent.deltaY;

  if (delta > 0) // going down
  else // going up

  return false;
});
Shikkediel
  • 5,195
  • 16
  • 45
  • 77
1

This disables the scrolling.

NOTE: Notice it only stops scrolling if you hover over the element.

$('#container').hover(function() {
    $(document).bind('mousewheel DOMMouseScroll',function(){ 
       console.log('Scroll!'); 
       stopWheel(); 
    });
}, function() {
    $(document).unbind('mousewheel DOMMouseScroll');
});


function stopWheel(e){
    if(!e){ /* IE7, IE8, Chrome, Safari */ 
        e = window.event; 
    }
    if(e.preventDefault) { /* Chrome, Safari, Firefox */ 
        e.preventDefault(); 
    } 
    e.returnValue = false; /* IE7, IE8 */
}

Quoted from amosrivera's answer

EDIT: To check which way it is scrolling.

var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st;
});
Community
  • 1
  • 1
Alexey
  • 3,607
  • 8
  • 34
  • 54
  • 1
    I have to add - if the page isn't actually going to be scrolled, the second script will not work. – Shikkediel Apr 15 '15 at 17:17
  • You are right. But since there is still no feedback from OP, I can't guess why such functions are needed. – Alexey Apr 15 '15 at 17:20