Search code examples
jqueryhtmlcssscrollposition

Div with position fixed until certain height glitching


I'm having trouble fixing a script that scrolls down with the page and stops on a specific height. Right before it reaches the point it needs to be on position absolute again, it disappears for a moment and appears right after.

Here's an example of the code:

$(document).scroll(function () {
    var y = $(this).scrollTop();

    if (y > 280 && y < 1600) {
        $('#model').css("position","fixed");
        $('#icons').css("position","fixed");
        $('#icons').css("bottom",0);
    } else if (y >= 1601) {
        $('#model').css("position","absolute");
        $('#model').css("top",1600);
        $('#icons').css("position","absolute");
        $('#icons').css("top",1600);
    } else {
        $('#model').removeAttr( 'style' );
        $('#icons').removeAttr( 'style' );
        $('#icons').removeAttr( 'style' );
    }   
});

Any help is appreciated!


Solution

  • The glitch that you are referring to might be caused by either of the two conditions:

    1. For the first condition, you have a scrollTop range between 280 & 1599 (< 1600), and further >= 1601. This leaves a blank area on the scrollTop position 1600 itself.
    2. When you scroll back from the bottom to top, the #model div's top is not set back to the original state (0), and it somehow wanders to it's containers boundaries I suppose.

    Therefore, the following changes in your code should fix the issue:

    if (y > 280 && y < 1600) {
        $('#model').css("position","fixed");
        $('#model').css('top', 0);          // add this rule
        $('#icons').css("position","fixed");
        $('#icons').css("bottom",0);
    } else if (y >= 1600) {                 // change the condition to include range greater than or equal to 1600
        $('#model').css("position","absolute");
        $('#model').css("top",1600);
        $('#icons').css("position","absolute");
        $('#icons').css("top",1600);
    

    JSFiddle Demo.