Question:
How to remove the browser scroll when opening a menu, and after closing it, turn it back on? Found this solution, but I don't know how to turn it off after the menu closes:
document.onmousewheel = document.onwheel = function () {
return false;
};
document.addEventListener("MozMousePixelScroll", function () {
return false
}, false);
document.onkeydown = function (e) {
if (e.keyCode >= 33 && e.keyCode <= 40) return false;
};
return false;
Here is the link to the codepen
PS overflow: hidden; does not fit, because after canceling this property, it will scroll to the very top of the page.
Answer:
Take out the definition you need to scroll or not into an external variable and return it in your functions:
window.can_scroll = true;
document.onmousewheel = document.onwheel = function () {
return window.can_scroll;
};
document.addEventListener("MozMousePixelScroll", function () {
return window.can_scroll
}, false);
document.onkeydown = function (e) {
if (e.keyCode >= 33 && e.keyCode <= 40) return window.can_scroll;
};
Or remove listeners:
// выключить скролл
document.onmousewheel = document.onwheel = function () {
return false;
};
function scrollOrNot() {
return false;
}
document.addEventListener("MozMousePixelScroll", scrollOrNot, false);
document.onkeydown = function (e) {
if (e.keyCode >= 33 && e.keyCode <= 40) return window.can_scroll;
};
// включить скролл
document.onmousewheel = document.onwheel = function () {
return true;
};
document.onkeydown = function (e) {
return true;
};
document.removeEventListener("MozMousePixelScroll", scrollOrNot, false);