Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch mousewheel up or down with jQuery/JS, without actually scrolling

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 */ }
});
like image 357
Enzio Rossa Avatar asked Apr 15 '15 14:04

Enzio Rossa


2 Answers

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;
});
like image 70
Shikkediel Avatar answered Oct 19 '22 23:10

Shikkediel


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;
});
like image 26
Alexey Avatar answered Oct 20 '22 01:10

Alexey