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

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


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();​

You can do this way: http://jsfiddle.net/gUWdJ/1/

$(window).scroll(function() {

    if ($(this).scrollTop() < $('section[data-anchor="top"]').offset().top) {
       $('nav a').removeClass('active');
    }

    if ($(this).scrollTop() >= $('section[data-anchor="top"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(0)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="news"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(1)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="products"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(2)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="contact"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(3)').addClass('active');
    }

});