3

I've done plenty of research into this and I can't seem to figure out why this isn't working for me.

I have two div elements. One of these divs has position: fixed to keep it in the window at all times.

Once the div hits the footer, it should remove the fixed scrolling and stick to the top of the footer. I've tried using the code found in this example, but the div just snaps back up to the top of the page when it reaches the footer.

Here's a fiddle for an example:

$(document).scroll(function (){
  if($('.userInfo').offset().top + $('.userInfo').height() >= $('footer').offset().top - 10){
    $('.userInfo').css('position', 'absolute');
  }
        
  if($(document).scrollTop() + window.innerHeight < $('footer').offset().top){
    $('.userInfo').css('position', 'fixed');
  } 
});
.profileMain{
    display: flex;
}

.userInfoContainer{
    height: 100%;
    width: 50%;
    display: inline-block;
}

.userInfo{
    background: red;
    width: 50%;
    position: fixed;
}

.userContent{
    background: blue;
    width: 50%;
    margin-bottom: 10em;
}

footer{
  background: gray;
  width: 100%;
  height: 30em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class = "profileMain">
  <div class = "userInfoContainer">
    <div class = "userInfo">f</div>
  </div>
  <div class = "userContent">f</div>
</div>

<footer></footer>

Can someone explain to me what I'm doing wrong here?

Jaxon Crosmas
  • 437
  • 1
  • 4
  • 14
  • I don't see where you are setting the top position when you swap to position:fixed. Its going to default to the top of the page. To fix, in your footer css, set the top and left position where you need them to be. – Korgrue Apr 10 '18 at 22:41
  • @Korgrue I'm not sure what you mean. Is this not a problem with the jQuery code? I've tried setting `bottom: 0` when it hits the footer, but that didn't do anything either. – Jaxon Crosmas Apr 10 '18 at 22:46

1 Answers1

2

to do the opposite of the example you provided ( sticking the div to the top and not to bottom ) , remove the window.innerHeight from the second if and compare the scroll + the element's height with offset of the footer, and use top and bottom positionning to place the div where you want,

this should do the trick :

$(document).scroll(function() {
  if ($('.userInfo').offset().top + $('.userInfo').height() >= $('footer').offset().top - 10)
    $('.userInfo').css({
      'position': 'absolute',
      'bottom': 0,
      'top': 'auto'
    });

  if ($(document).scrollTop() + $('.userInfo').height() < $('footer').offset().top)
    $('.userInfo').css({
      'position': 'fixed',
      'top': 0,
      'bottom': 'auto'
    }); // restore when you scroll up
});

here's a fiddle : https://jsfiddle.net/xpvt214o/93144/

Taki
  • 17,320
  • 4
  • 26
  • 47