I want to prevent the user from scrolling via mouse wheel. In Firefox it works but not in Chrome. What must be changed for Chrome?
$(window).on(\'wheel\', functi
You need to set the event handler to non-passive for it to work on Chrome. That is not possible in jQuery as far as I know. But you can use the regular addEventListener
for this.
document.addEventListener('wheel', function(e) {
e.preventDefault(); // Prevent user scroll during page jump
}, {
passive: false
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
height: 2000px;
}
<div id="banner-message">
<p>Mousewheel should be prevented</p>
</div>
As pointed out by Shikkediel in the comments: if you want to support older (versions of) browsers (for example Internet Explorer), it is recommended to first check if the passive
option is supported by the browser. Older browsers had a boolean type as the third parameter of the addEventListener
. Therefore they might throw an error, or they could set the third parameter to true (default is false) which might cause some undesired behavior. You can use the code below for that.
var passiveSupported = supportsPassive();
document.addEventListener('wheel', function(e) {
e.preventDefault(); // Prevent user scroll during page jump
}, passiveSupported ? {
passive: false
} : false);
function supportsPassive() {
var passiveSupported = false;
try {
var options = {
get passive() {
passiveSupported = true;
}
};
window.addEventListener("test", options, options);
window.removeEventListener("test", options, options);
} catch (err) {
passiveSupported = false;
}
return passiveSupported;
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
height: 2000px;
}
<div id="banner-message">
<p>Mousewheel should be prevented</p>
</div>