Search code examples
jquerypositionfixednavbar

JQuery Position:Fixed 'NAVBAR' by scrolling the page


Basically I want my NAVBAR to stay at the top of the window position:fixed as soon as the #CONTENT DIV under the NAV get to the top of the window.

The HTML is

<header>
Which is full screen size: 100% x 100%
</header>

<nav>
</nav>

<div id="content">
<section>
</section>

<footer>
</footer>
</div>

Here you can find the DEMO http://jsfiddle.net/dcdeiv/aG6DK/2/ Everything works fine, except the jQuery code.

I tried to create a variable from the return of the height value of the #contentDiv while scrolling. I wanted to use that variable to make the NAV fadeIn or fadeOut as soon as the #contentDiv reaches the top of the window but it does not work

$(document).scroll(function () {
    var x = $('#content').scrolltop();
    if (x = 0) {
        $('nav').fadeIn().css({"position":"fixed","top":"0"});
    } else {
        $('nav').fadeOut();
    }
});

Can you please help me? It is the first time with jQuery to me, so please be indulgent and explain me all of my mistakes!

plus I am Italian so don't be grammar nazi! LOL

Thank you.


Solution

  • Here is the code that I got to work:

    $(document).ready(function() {
        $(document).scroll(function () {
            var scroll = $(this).scrollTop();
            var topDist = $("#container").position();
            if (scroll > topDist.top) {
                $('nav').css({"position":"fixed","top":"0"});
            } else {
                $('nav').css({"position":"static","top":"auto"});
            }
        });
    });
    

    DEMO

    These are the syntactical mistakes:

    • .scrolltop() should be .scrollTop()
    • if(x = 0) should be if(x == 0) (or not, see above code)

    Also, in jsfiddle, you have to specify a library in the upper left hand corner in order for jQuery to work.

    jsfiddle jQuery library

    Your logic also needs a little help.

    1. .scrollTop() only gets the position of the scroll bar of the page. This means that it starts off at 0. Thus, the code you have would stick the navigation to the top as soon as the user tried to scroll.
    2. We need the nav to stick once it has reached the top, so we need to know how far it is from the top. var topDist = $("#container").position(); creates an object that has both the `top` and `left` properties of the container. We can then retrieve the top by topDist.top.
    3. Now that we have the scroll position (.scrollTop) and how far down the page the `nav` is, we can compare the two and then run your original actions.

    As a side note, your fadeIn() and fadeOut() are not really necessary. I am not quite sure what you were trying to accomplish, but you can just omit them.