Make content sticky on scroll to a point in jQuery
Asked Answered
F

3

9

I have a div that's set to position: relative. It becomes fixed when the top of the window reaches it. The div lives in a container (blue in the example below) and I would like to set it back to relative when it reaches the bottom of its parent container (blue).

This is my code simplified and my Fiddle:

HTML:

<div class="green"></div>

<div class="blue">
  <div class="sticky">Sticky</div>
</div>

<div class="red"></div>

CSS:

.blue {
  background-color: blue;
  height: 500px;
}

.sticky {
  width: 200px;
  background-color: yellow;
  text-align: center;
  top: 0;
}

.red {
  background-color: red;
  height: 800px;
}

.green {
  background-color: green;
  height: 200px;
}

And the jQuery:

$(document).ready(function() {
  var stickyTop = $('.sticky').offset().top;

  $(window).scroll(function() {
    var windowTop = $(window).scrollTop();

    if (stickyTop < windowTop) {
      $('.sticky').css('position', 'fixed');
    } else {
      $('.sticky').css('position', 'relative');
    }
  });
});
Frisby answered 18/1, 2016 at 0:12 Comment(0)
E
15

Add following condition to your if statement:

$(".blue").height() + $(".blue").offset().top > windowTop

Your code should look like this:

$(document).ready(function() {
  var stickyTop = $('.sticky').offset().top;

  $(window).scroll(function() {
    var windowTop = $(window).scrollTop();
    if (stickyTop < windowTop && $(".blue").height() + $(".blue").offset().top - $(".sticky").height() > windowTop) {
      $('.sticky').css('position', 'fixed');
    } else {
      $('.sticky').css('position', 'relative');
    }
  });
});

See updated JSFiddle.

Exterminatory answered 18/1, 2016 at 0:33 Comment(0)
R
0

you can make it with jquery.sticky.js plugin

add an id to the element you want to stick

$('#sticky').sticky();
Reannareap answered 22/2, 2022 at 8:22 Comment(0)
B
-1

Here is a solution:

$(window).scroll(function() {
       var navpos1 = $('.header').offset().top(); 
           if (navpos1) {
              $('body').addClass('fixedHd');
            } else {
                 $('body').removeClass('fixedHd');
                 }
  });  
Balls answered 13/2, 2020 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.