zozo zozo - 5 months ago 24
jQuery Question

keep a div to the bottom of the page until scroll gets to a certain position

I have the following setup:


  • A big html page (so scroll is there)

  • Inside it near the bottom a div... let's call it positionDiv:
    <div id="positionDiv">Lalala</div>

  • Another div called lets say... floatingDiv:
    <div id="floatingDiv">Lalala</div>



What I need to do is to keep
floatingDiv
to the bottom of the page (easy doable with a position: fixed) until it gets (after scrolling) on top of the
positionDiv
(here the position fixed fails since the div will stay at the bottom forever).

Any idea how to do that?

Answer

jQuery exposes an offset method which can help here.

EDIT: improved code, working example.

$(function fixedUntilPoint(){
  var positionDiv = $('#positionDiv');
  var floatingDiv = $('#floatingDiv');

  function testScrollPosition(){ 
    var positionOffset = positionDiv.offset().top;
    var floatingOffset = floatingDiv.offset().top;

    if(positionOffset <= floatingOffset){
      floatingDiv.css({
        bottom:   'auto',
        position: 'absolute',
        top:      positionDiv.offset().top
      })
    }
    else {
      floatingDiv.css({
        bottom:   0,
        position: 'fixed',
        top:      'auto'
      })
    }
  }

  $(window).on('scroll resize', testScrollPosition)

  testScrollPosition();
})