I have been looking for a solution that would work for a good while now but honestly everything I try falls short. I have built a website and would like to prevent the user from scrolling past 6200px from the top (the page is around 8240px long). It’ll be long to explain why I need help with this but basically, it’s some patchwork that’s needed to be done. I understand CSS and JS but my JS isn’t amazing…A lot of the answers I have seen before are in jQuery, which is fine but I would appreciate some explanation on how to implement it into my HTML as I’m kind of new to the coding game.
Any help would be amazing! Thanks!
Advertisement
Answer
The problem with sensing the scroll event and acting on just that is that the user may have shot past the 6200px point as you don’t get told about the event until the scrolling has happened. So for example think of a very fast intertial scroll on a tablet – finger flicking wildly to go down.
So we need to make sure that if they do shoot past they don’t see anything.
We can do these things:
- Hide everything below 6200px with a pseudo div – can’t stop a nosey user looking at what’s underneath using browser dev tools, but can stop people accidentally seeing the stuff that’s there
- Plant a 1pixel div at 6199px and set up an intersectionObserver on it so we know when the user is entering the danger zone and force scrollTo just to show the final viewport’s worth of ‘allowed’ content.
function callback(entries) { if (entries[0].isIntersecting) { window.scrollTo({top: Number(6200 - window.innerHeight), left: 0, behavior: 'smooth'}); } } const observer = new IntersectionObserver(callback); observer.observe(document.querySelector('#sensor'));
body { position: relative; } .talldiv::after { height: calc(100% - 6200px); width: 100%; content: ''; background-color: white; position: absolute; top: 6200px; left: 0px; z-index: 99999; } #sensor { position: absolute; width: 1px; height: 1px; left: 50%; top: 6199px; } .talldiv { width: 100vw; height: 8000px; background-image: linear-gradient(to bottom, red, purple, orange, yellow, green, blue, cyan, magenta, gray); }
<div id="sensor"></div> <div class="talldiv">SCOLL DOWN</div>
I had thought that we shouldn’t have to do any more but on a laptop it has been possible to ‘break through’ and scroll past 6200px if scrolling fast in large chunks. I need to add a bit to sense when the sensor has gone off the top of the viewport rather than just when it comes into the viewport.