-1

Please look at this other question first: Mouse wheel scroll event and the demo from the accepted answer.

How can I reduce the jitter when a scroll event is canceled?

Community
  • 1
  • 1
Bruce Li
  • 137
  • 4
  • 13

1 Answers1

2

Demo: http://jsfiddle.net/HUGTL/

Building on the answer to your original question, you could do something like:

var noscroll = document.getElementById('noscroll');

var locked, lockedX, lockedY;
noscroll.addEventListener('mouseover', function (){
    locked = true;
    lockedX = window.scrollX;
    lockedY = window.scrollY;
}, false);
noscroll.addEventListener('mouseout', function (){
    locked = false;
}, false);

// changes

$(window).on("mousewheel keydown", function(e){
    if(locked === true){
        return false;
    }
});

$(window).on("scroll", function(e){
    if(locked === true){
        // add fallback here for other scenarios
    }
});

I'm using jQuery to simplify/standardize event handling.

Note that prevent key events may not be desirable; I included that to show how arrow keys could be prevented (you could also check for specific key codes).

I also added a general fallback handler for scenarios not handled by mousewheel/keydown.

This may not work well (or at all) with touch events. Most importantly, make sure that it doesn't confuse your users or remove expected functionality.

If you only want to handle the mousewheel, it may be much simpler:

$("#noscroll").on("mousewheel", function(e){
    return false;
});

Demo: http://jsfiddle.net/HUGTL/3/. However, this doesn't work for key events.

Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163
  • The time to spent is a bit long,I make a try,the same result.The question is how can I reduce the jitter when a scroll event is canceled?Like in a map,when I roll the mouse wheel,the page doesn't have a jitter effect. – Bruce Li Dec 28 '12 at 02:27
  • I think the only way is to cancel the event before the scroll occurs (e.g. returning false `onmousewheel/keydown`). I couldn't find a way to smooth it once the scroll had started. – Tim M. Dec 28 '12 at 02:33
  • Ok,I know your meaning.Thank you for your advice,I will try it. – Bruce Li Dec 28 '12 at 02:35
  • Regarding the maps (at least Google maps) looks like they handle all the events and never let them bubble to the window for scrolling. So they respond to mousewheel, clicking, dragging, etc. move the map around and return false. – Tim M. Dec 28 '12 at 02:35
  • That is the final effect what I want to do,haha. – Bruce Li Dec 28 '12 at 02:38