Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent mouse wheel scrolling, but not scrollbar event. JavaScript

I need to make a webpage scrollable only by scrolling bar. I have tried to find how to catch scroll bar event, but as i see it is impossible. Currently i use this functions:

function preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}
function wheel(e) {
    preventDefault(e);
}
function disable_scroll() {
    if (window.addEventListener) {
        window.addEventListener('DOMMouseScroll', wheel, false);
    }
    window.onmousewheel = document.onmousewheel = wheel;
}

But they are not very useful in my situation, because they block all scroll events. Do you have any ideas? I am thinking about it 3 days already and i didn't find any answer (and questions also). Thanks!

like image 432
user2998173 Avatar asked Nov 17 '13 02:11

user2998173


People also ask

How do I temporarily disable my scroll wheel?

Open the Settings app (Win+I keyboard shortcut) and click the "Devices" category on the homepage. From the sidebar on the left, click or tap the "Mouse" page to view mouse settings. At the bottom of the page, toggle the "Scroll inactive windows when I hover over them" option to "off" to disable the feature.

How do I stop a scroll event?

Every event on Jquery has a method called preventDefault() , that according to the Jquery Docs: Show activity on this post. You can try to return false at the end of your custom scroll function, or call preventDefault() before calling your custom scroll function.

How do I stop scrolling when scrolling a div element CSS?

To hide the horizontal scrollbar and prevent horizontal scrolling, use overflow-x: hidden: HTML. CSS.

How do I stop my mouse wheel from scrolling in jquery?

Try using . unmousewheel() , it should also work.


1 Answers

To prevent window scrolling with mouse wheel.

// Old Method
window.onwheel = function(){ return false; }

EDIT (Jan 2020): As informed by @MatthewMorrone above code to bind wheel event on window, window.document & window.document.body (marked as 'Old Method') is no longer working. For more details please check: https://www.chromestatus.com/features/6662647093133312

As document level Wheel/Mousewheel event listeners are treated as Passive, we need to mark this event listener to be treated as Active. Please check below code for the solution. More about: https://developers.google.com/web/updates/2019/02/scrolling-intervention

// New Working Method
window.addEventListener("wheel", e => e.preventDefault(), { passive:false })

If a content of <div> or other element is scrollable, you can prevent it like this:

document.getElementById('{element-id}').onwheel = function(){ return false; }

Cheers...

like image 87
Saurin Dashadia Avatar answered Oct 05 '22 01:10

Saurin Dashadia