Home > Net >  jQuery "unstick" box when scrolling before a certain threshold
jQuery "unstick" box when scrolling before a certain threshold

Time:09-21

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!

CodePudding user response:

if ( windowTop > xxx ) here the .scrollTop() will run until the page end because all variables are running inside $(window).scroll(function() {}.

So I think you need to run it inside $(document).ready(function() and you can implement two conditions for if block. If threshold reach top then switch to else statement.

Demo :

$(document).ready(function() {
    var box = $(".box");
    var pos = box.position();           
    var stickyTop = $('.threshold').offset().top;
    $(window).scroll(function() {
        var windowTop = $(window).scrollTop();
        if (windowTop >= pos.top & windowTop <=stickyTop) {
            box.addClass("sticky");
        } else {
            box.removeClass("sticky");  
        }
    });
});
header {
  height:500px;
  background: orange;
}
.page {
    background:#efe;
  height: 3900px;
}

.sticky {
    position:fixed;
    top:0px;
}
.threshold {
  position: absolute;
  top: 1000px;
  font-size: 2em;
  background: red;
  color:black;
}
.box {
  width: 300px;
  height: 300px;
  background: green;
  display: flex;
  flex-direction:column;
    padding:20px;
  box-sizing:border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header></header>
<div >
    <div ></div>
    <div >threshold </div>
</div>

CodePudding user response:

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