Event scroll
can not cancel. This is very clear in the W3C specification .
The only ways I know to get around this are:
-
overflow: hidden;
- an event dropper that forces the scroll position to not change
The first option to give overflow: hidden;
in the body is often used in cases where scroll
should not happen. In your case you want the scroll
to work until a certain time and then stop working. To use this idea you have to read the scroll position and apply overflow: hidden;
to body
or parent element of the other.
Example:
CSS
div {
height: 4000px;
border: 1px solid #ccf;
}
.pararScroll {
overflow: hidden;
background-color: #eee;
}
JS
window.addEventListener('scroll', function (e) {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (scrollTop > 1000) document.body.classList.add('pararScroll');
});
jsFiddle: link
The second option needs you to save the value of the last scroll position. So at every scroll
event, you say again that the position should be the previous to that scroll
event.
Example:
var lastScroll;
window.addEventListener('scroll', function (e) {
if (lastScroll) return window.scrollTo(0, lastScroll);
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (scrollTop > 1000) lastScroll = scrollTop;
});
jsFiddle: link
And if you want to re-enable scroll, you only have to change the value of lastScroll
to a value that has boolean false
.