Skip to content
Advertisement

Block scrolling up past a certain div using css / js

I am trying to figure out how to limit a visitor’s scrolling back up to stop at div2, not the top of the webpage.

The webpage has several main sections:

<div1>tease</div>
<div2>hero</div>
<div3>info</div>
<div4>specs</div>
<div5>prices</div>
<footer></footer>

div1 is purely a marketing teaser to get the visitor curious, something they only need to see once. Ideally we want to be able to trigger the scroll limits once the visitor has worked their way down the page to div3. Then when they scroll back up, the page stops with the hero at the top, as if the tease doesn’t exist.

We tried simply hiding the div as you scrolled down, but that causes the page to be redrawn with huge content shift (the tease fills 100% of the viewport height, with a max-height value). That UI shift is not desirable. Triggering hiding the div at the bottom of the footer would avoid the redraw shift, but most visitors don’t scroll all the way to the bottom of the footer.

We looked at using css animation to slowly reduce the height of div1, but again it makes the UI jerky due to redrawing.

I am looking for a way to do this with css and javascript. Don’t want to load jQuery for one marketing trick. Thanks.

Advertisement

Answer

We solved the quandary by making the hero image (div 2) sticky and adding top margin to info (div 3).

By making the hero image sticky, it froze when it reached the top of the viewport and thus was unaffected by the redrawing caused by closing the tease (div 1). We used InterectionObserver to watch for div 3 reaching the viewport and triggered closing of div 1 and adding top margin to div 3.

  // close tease and push div 3 down to avoid content jump
  const target = $('div3');
  function handleIntersection(entries) {
    entries.map((entry) => {
      if (entry.isIntersecting) {
        $('div1').style.display = 'none';
        $('div3').style.marginTop = '100vh';
      } else { }
    });
  }
  const observer = new IntersectionObserver(handleIntersection);
  observer.observe(target);

If someone were watching the scroll bar on their browser they would notice it moving during the redrawing, but the info in the viewport remains stationary.

We decided to add the top margin via js, as we didn’t want a huge blank on the webpage for the few visitors who might have javascript disabled.

Advertisement