Lost Fixed Position on page load jQuery

98 views Asked by At

Right now I have a script that's similar to this jsFiddle: Fixed on Scroll

Now if I scroll down it works. But if I refresh the page, the fixed elements disappear until I do a scroll.

I've thought about if the $(window) > 0 then show it with a if statement. And nothing. Just would like help in the right direction.

Thanks.

2

There are 2 answers

2
Cymen On

Given your page is the same as the JSFiddle, I would suggest hooking into the ready event of the page and running the same function that is being run on scroll. So it would look like:

$(document).ready(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('#navigation').css('position','fixed').css('top','0');
        } else {
            $('#navigation').css('position','static');
        }    
});
0
halbgut On

I'd put the control-structure into a function and run in onscroll and onready

var elementPosition = $('#navigation').offset();

$(window).scroll(shouldStickHeader);
$(document).ready(shouldStickHeader);

function shouldStickHeader () {
    if($(window).scrollTop() > elementPosition.top){
          $('#navigation').css('position','fixed').css('top','0');
    } else {
        $('#navigation').css('position','static');
    }
}