jquery scroll, change navigation active class as the page is scrolling, relative to sections

Joshc picture Joshc · Jan 4, 2013 · Viewed 71.6k times · Source

http://jsfiddle.net/motocomdigital/gUWdJ/


I'm after a jquery scroll technique please that I would like to adapt to my project.

Please see my project example as a fiddle here http://jsfiddle.net/motocomdigital/gUWdJ/

Currently you can see that my nav links automatically animates the scrolling relative to the <section>'s.

My question is, using the $(window).scroll method, how can I add a .active class to my nav a when the sections reach the top of the window?

So for example if the user scrolls down the page (instead of the navigation links), I want the active class to be added relative navigation link. Indicating where you are on the page.

The active class will have to be removed then added every time I'm guessing as the user scrolls down the page.

Also you will have to account for the 28px height of the fixed navigation bar, offset top window.


Can anyone please show me a technique that I can try and use or adapt, or perhaps show me using my jsfiddle :)


Any help would be much appreciated, thanks in advance!


http://jsfiddle.net/motocomdigital/gUWdJ/


enter image description here

Answer

A. Wolff picture A. Wolff · Jan 4, 2013

If you wish a more generic function:

SEE DEMO

$(window).scroll(function() {
    var windscroll = $(window).scrollTop();
    if (windscroll >= 100) {
        $('nav').addClass('fixed');
        $('.wrapper section').each(function(i) {
            if ($(this).position().top <= windscroll - 100) {
                $('nav a.active').removeClass('active');
                $('nav a').eq(i).addClass('active');
            }
        });

    } else {

        $('nav').removeClass('fixed');
        $('nav a.active').removeClass('active');
        $('nav a:first').addClass('active');
    }

}).scroll();​