Skip to content Skip to sidebar Skip to footer

Javascript Fixed Position Nav Works Intermittently Depending On Window Height/amount Of Scroll

I have a header image above a navigation bar, the header image is comprised of two images, the one in the foreground is in the lower-left, and scrolls with the background until it'

Solution 1:

Finally, I found it.

The issue was that I was letting the main body of content 'jump' up behind the navigation is soon as it stuck.

I actually didn't notice this behaviour at first - since I was just using a load of <br />s to fill some dummy content.

So, when the window size was big enough to allow scrolling down to meet the #nav div, and slightly beyond, but not so large as to have content beyond the amount by which it jumps up behind #nav, the browser would not let it scroll beyond the end of the page, and thus 'jumps' back up.

My fix is to cloak #nav in some outer #sticky-nav{ min-height: /*height of everything that sticks to top */ }.

Simple, but it works. jQuery is the same, we're still detecting off and sticking #nav, but now the content won't jump behind it, so it won't flicker when there's an amount of scroll somewhere between 0 and nav height.

Here's the fiddle.

Solution 2:

else{
            $('#fg-img').css({ 'position': 'fixed', 'top': -247});
        }

change in

elseif (scroll_top < ('you condition')  ){
            $('#fg-img').css({ 'position': 'fixed', 'top': -247});
        }

Solution 3:

Solution

Tried to dry the elements as much as possible for a clean solution. Notice that if you remove the block display from the images you will have to set the line-height or you might end up with a space between the elements.

HTML

<divid="header"><imgsrc="http://placehold.it/960x300" /></div><divid="nav"><imgsrc="http://placehold.it/960x80/000000" /></div><ol><li>item</li><li>item</li>
  ...
</ol>

CSS

body {margin: 0}
img {display: block}
ol {margin: 10px; padding: 00020px}

JS

var$nav = $('#nav'), 
    $header = $('#header'),
    $window = $(window),
    height = $nav.height(),
    top = $nav.offset().top,

nav = function () {  
  var scroll = $window.scrollTop(); 
  if (top < scroll) {
    $nav.css({ 'position': 'fixed', 'top': 0});        
    $header.css({ 'margin-bottom': height + 10 });
    //10 is the bottom margin of the next element
  } else {
    $nav.css({ 'position': 'relative' });
    $header.css({ 'margin-bottom': 0 });
  }
};  

nav();
$window.scroll(nav);

Post a Comment for "Javascript Fixed Position Nav Works Intermittently Depending On Window Height/amount Of Scroll"