Search code examples
jquerycssscrollwidthfixed

Div becomes fixed after scroll at set pixel count from top, also only greater than set window width, plus adds border-bottom


I am using a script (below) that allows a (navigation) div to scroll but once it gets to the top of the browser it becomes fixed. I want the div to become fixed 50 pixels from the top of the window which the script does, but it has to reach the very top first before it then jumps down.

I would like it to stop and become fixed 50 pixels BEFORE it actually reaches the top..

<script type="text/javascript">
var fixmeTop = $('.navPages-container').offset().top;
$(window).scroll(function() {
    var currentScroll = $(window).scrollTop();
    if ((currentScroll >= fixmeTop) && ($(window).width() > 800))  {
        $('.navPages-container').css({
            position: 'fixed',
            top: '52px',
            height: '50px',
            left: '0'
        });
    } else {
        $('.navPages-container').css({
            position: 'static',
            top: '0'
        });
    }
});
</script>

Now I found another script which does exactly this (below), however I want to combine both scripts, so that this functionality only occurs when the browser window width is > (greater than) 800 (see first script).

Also, once the div becomes fixed a bottom border appears: border-bottom: 1px solid #000 (I understand that dashes are not allowed).

<script type="text/javascript">
var fixed = false;
$(document).scroll(function() {
    if( $(this).scrollTop() >= 118 ) {
        if( !fixed ) {
            fixed = true;
            $('.navPages-container').css({
               position:'fixed',
               top:50
            });
        }
    } else {
        if( fixed ) {
            fixed = false;
            $('.navPages-container').css({
               position:'static'
            });
    }
}
});
</script>

Any help is appreciated!


Solution

  • You could try this. I've just added the conditional statement regarding width from the first script to the second script. Also added the black border into the CSS statement that occurs when the conditions are true

    <script type="text/javascript">
    var fixed = false;
    $(document).scroll(function() {
    if( $(this).scrollTop() >= 118 && ($(window).width() > 800) ) {
        if( !fixed ) {
            fixed = true;
            $('.navPages-container').css({
               position:'fixed',
               top:50,
    
            });
     $('.navPages-container').css('border-bottom','1px solid #000');
        }
    } else {
        if( fixed ) {
            fixed = false;
            $('.navPages-container').css({
               position:'static'
            });
     $('.navPages-container').css('border-bottom','0px');
        }
    }
    });
    </script>