jQuery "unstick" box when scrolling before a certain threshold

Viewed 52

I have a box that needs to stick, and I am using position: fixed CSS for that when it reaches the bottom of the page while scrolling, and then unstick while scrolling back up past that threshold. Below is my jQuery code:

$(window).scroll(function() {
  var wHeight = $(window).height();
  var stickyTop = $('.threshold').offset().top;
  var xxx = stickyTop - wHeight;
  var windowTop = $(window).scrollTop();

  if ( windowTop > xxx ) {
    console.log(windowTop)
    $('.box').addClass("sticky")
  } else {
    $('.box').removeClass("sticky")
  }
});

I don't understand why my else state doesn't work. And it's weird that the console.log kicks in late.

Here's a complete pen: https://codepen.io/frontend2020/pen/vYjJBma?editors=1010

Thanks for helping!

1 Answers

This kind of sticking effect can be easily done with CSS. If you want something similar like this YouTube video which was captured on this site, you just need two nested divs (i.e.div>div).

The parent div must has larger height (let's say 1000px) and child div can be anything less than the parent div (let's say 200px). Then you just need to apply position: sticky; to child div.

That will do the trick.

Related