Mike W Mike W - 1 month ago 6
CSS Question

Prevent Scroll in one direction if scrolled to top or bottom div

I have a scrollable div and I would like to prevent the user from scrolling down any farther once they reach a certain point and only allow them to scroll back up without jquery

fixed.addEventListener('mousewheel', function(e) {
if((fixed.scrollTop;+500)>fixed.scrollHeight;){
e.preventDefault();
}
}, false);


Currently what I have does the job of stopping scrolling all together once it reaches that point. Once it enters the if statement I want the user to be able to scroll back up. Not stop all scrolling

Answer

The mousewheel event is not standard, see https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel

However even if it was, your solution wouldn't cover touch devices for example, or scrolling by dragging the scroll bar. And in general once scrolling is in progress it can't be stopped, you can prevent it from happening in the first place, for example on touch devices:

window.addEventListener('touchmove', function(e) {
    e.preventDefault();
});

However it is very bad practice as it turns off scroll and zoom completely.

The problem you have is that you cannot determine the direction of scroll before it has happened. The only way I would see it is to look at the scroll event, determine if the page scroll is upwards or downwards and then set scrollTo on the element if you would like that not to happen, but it may cause an awkward jump.

For example:

var lastScrollPosition = fixed.scrollTop;

fixed.addEventListener('scroll', function () {
    var goingDown = (fixed.scrollTop - lastScrollPosition) > 0;
    /* If scrolling down the new scrollTop will be larger
        than the last one so it will be a positive number
        and we want to stop that from happening
    */
    var maximumScrollReached = (fixed.scrollTop + 500 > fixed.scrollHeight);

    if (goingDown && maximumScrollReached) {
        fixed.scrollTop = lastScrollPosition; // Or whatever maximum you want to allow
    }

    lastScrollPosition = fixed.scrollTop;
});

Mind that the scroll event can fire A LOT, so you might consider wrapping it in some kind of debounce function like https://lodash.com/docs/4.16.4#debounce or write one yourself

Also why are you considering this? There might be better solutions to your original problem, maybe some pure CSS ones.

Comments