I have a sidebar on my site that occasionally needs to be scrolled. It’s an unpleasant user experience when, after scrolling the sidebar to the bottom with the mousewheel, the main window begins to scroll.
I’d like to make sure the main window does not scroll with the mouse wheel when the mouse wheel is over my sidebar, though preferably only when my sidebar itself is showing scrollbars.
I’d probably like to avoid use of javascript scroll bars as they seem to often not perform as well as the defaults (laggier, wait on other js code, etc), though it looks like this solution may require them.
Thanks!
EDIT::
Here’s the code I ended up using, a simple adaptation of what I found in the first link from my accepted answer.
(function($) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.height();
}
})(jQuery);
/** This is high-level function.
* It must react to delta being more/less than zero.
*/
function handle(delta) {
slider = $('#wl-slider');
if(slider.hasScrollBar()){
if (delta > 0 && slider.scrollTop() == 0 && slider.hasClass('scroll-hover')){
event.preventDefault();
event.returnValue = false;
}
else if (delta < 0 && (slider.get(0).scrollHeight - slider.scrollTop() == slider.outerHeight()) && slider.hasClass('scroll-hover')){
event.preventDefault();
event.returnValue = false;
}
}
}
/** Event handler for mouse wheel event.
*/
function wheel(event){
var delta = 0;
if (!event) /* For IE. */
event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta/120;
} else if (event.detail) { /** Mozilla case. */
/** In Mozilla, sign of delta is different than in IE.
* Also, delta is multiple of 3.
*/
delta = -event.detail/3;
}
/** If delta is nonzero, handle it.
* Basically, delta is now positive if wheel was scrolled up,
* and negative, if wheel was scrolled down.
*/
if (delta)
handle(delta);
}
/** Initialization code.
* If you use your own event management code, change it as required.
*/
if($('#user-level').size() != 0)
{
if (window.addEventListener)
/** DOMMouseScroll is for mozilla. */
window.addEventListener('DOMMouseScroll', wheel, false);
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = wheel;
}
I guess you won’t suffice with standard event handlers e.g. in jquery and you need to handle directly the mouse wheel – I just googled these resources:
And then look directly if the sidebar is already scrolled at the bottom/top and if yes, filter out the scroll event.