0

I've been trying to make my navbar stick to top when I scroll by it and achieved it. The only problem is that my content kind of kicks up when the navbar transition to position fixed is executed.

Here is an example of this behavior: http://jsfiddle.net/7HHa5/4/

JavaScript

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    if (window.pageYOffset > 70) {
        header.style.position = "absolute";
        header.style.top = pageYOffset + "px";
    } else {
        header.style.position = "";
        header.style.top = "";
    }
}

I am using bootstrap and jQuery.

How can I avoid this behavior?

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
Thegree0ne
  • 175
  • 1
  • 2
  • 11

1 Answers1

0

When you set the header to position: absolute, it leaves an empty space which gets filled by the content. You need to add a margin to the top of the content when the header becomes fixed, like this:

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    var content = document.getElementById("content");
    if (window.pageYOffset > 70) {
        header.style.position = "absolute";
        header.style.top = pageYOffset + "px";
        content.style.marginTop = '55px'
    } else {
        header.style.position = "";
        header.style.top = "";
        content.style.marginTop = '0'
    }
}

See http://jsfiddle.net/2EhLs/1/ for an example.

However, there is a better way.

Since you are already using Bootstrap, you should consider using the built-in Affix feature.

The best example is this one from another question:

$('#nav-wrapper').height($("#nav").height());

$('#nav').affix({
    offset: { top: $('#nav').offset().top }
});
Community
  • 1
  • 1
Moshe Katz
  • 15,992
  • 7
  • 69
  • 116