3

I'm using the below jQuery (answered by James Montagne) to begin fixed position scrolling after the user scrolls down 250px so that the element stays fixed to the top of the browser.

$(window).scroll(function(){
    $("#theFixed").css("top",Math.max(0,250-$(this).scrollTop()));
});

QUESTION: In addition, I'd like to stop the fixed position scrolling when the bottom of the scrolling fixed position element comes to the end of the parent div element. This way preventing the fixed position element from overflowing the parent element and getting cutoff.

My example code is here: http://jsfiddle.net/b43hj/2020/

<div>
    <div id="theFixed" style="position: fixed; top: 250px; background-color: red">
        0 SOMETHING<br />
        1 SOMETHING<br />
        2 SOMETHING<br />
        3 SOMETHING<br />
        4 SOMETHING<br />
        5 SOMETHING<br />
        6 SOMETHING<br />
        7 SOMETHING<br />
        8 SOMETHING<br />
        9 SOMETHING<br />
        10 SOMETHING<br />
        11 SOMETHING<br />
        12 SOMETHING<br />
        13 SOMETHING<br />
        14 SOMETHING<br />
        15 SOMETHING<br />
        16 SOMETHING<br />
        17 SOMETHING<br />
        18 SOMETHING<br />
        19 SOMETHING<br />
        20 SOMETHING<br />
        21 SOMETHING<br />
        22 SOMETHING<br />
        23 SOMETHING<br />
        24 SOMETHING<br />
        25 SOMETHING<br />
        26 SOMETHING<br />
        27 SOMETHING<br />
        28 SOMETHING<br />
        29 SOMETHING<br />
    </div>
    THIS IS A LONG SENTENCE THAT GOES PAST THE RED SOMETHINGS
    <br>
    THIS IS A LONG SENTENCE THAT GOES PAST THE RED SOMETHINGS
    <br>
    ... END
</div>

Screenshot: screenshot of issue

(Add-on question to this original question and answer: Stopping fixed position scrolling at a certain point?)

Community
  • 1
  • 1
dabra904
  • 163
  • 5
  • 17

1 Answers1

5

To prevent the fixed element from overflowing the parent element, I present this solution. Example code

$(window).scroll(function(){
    var scroll_top = $(this).scrollTop(); // get scroll position top
    var height_element_parent =  $("#theFixed").parent().outerHeight(); //get high parent element
    var height_element = $("#theFixed").height(); //get high of elemeneto
    var position_fixed_max = height_element_parent - height_element; // get the maximum position of the elemen
    var position_fixed = scroll_top < 250 ? 250 - scroll_top : position_fixed_max > scroll_top ? 0 : position_fixed_max - scroll_top;
    $("#theFixed").css("top",position_fixed);
});
zoranc
  • 2,410
  • 1
  • 21
  • 34