views:

215

answers:

1

I'm using the $(window).scroll(function() to set classes on the navigation of a site. When a section rolls into view the navigation class changes to 'current'.

$(window).scroll(function() {

                var top = 0;
                top = $(window).scrollTop();

                if(top < 1000){
                    $("a[href='#uk']").parent().addClass("current");
                    $("a[href='#uk']").parent().siblings().removeClass("current");
                }
                if((top >= 1000) && (top < 2000)){
                    $("a[href='#mcr']").parent().addClass("current");
                    $("a[href='#mcr']").parent().siblings().removeClass("current");
                }    
                if((top >= 2000) && (top < 3000)){      
                    $("a[href='#lpool']").parent().addClass("current");
                    $("a[href='#lpool']").parent().siblings().removeClass("current");
                }
                if((top >= 3000) && (top < 4000)){      
                    $("a[href='#bham']").parent().addClass("current");
                    $("a[href='#bham']").parent().siblings().removeClass("current");
                }
            });  

This works great, however it works when the window is "scrolled" into place (obviously). If the page is refreshed then the class is removed even though the page remains at a certain section.

How would I get this code to check where it is on page load and apply the class immediately?

A: 
   //call it every load.. to fix your problem...
    fix();

    $(window).scroll(fix); //then bind it on window scroll..

 

function fix(){
     var top = 0;
     top = $(window).scrollTop();

     if(top < 1000){
          $("a[href='#uk']").parent().addClass("current");
          $("a[href='#uk']").parent().siblings().removeClass("current");
     }
     if((top >= 1000) && (top < 2000)){
          $("a[href='#mcr']").parent().addClass("current");
          $("a[href='#mcr']").parent().siblings().removeClass("current");
      }    
      if((top >= 2000) && (top < 3000)){      
          $("a[href='#lpool']").parent().addClass("current");
          $("a[href='#lpool']").parent().siblings().removeClass("current");
      }
      if((top >= 3000) && (top < 4000)){      
          $("a[href='#bham']").parent().addClass("current");
          $("a[href='#bham']").parent().siblings().removeClass("current");
      }
}
Reigel
Thanks for this, only I can't seem to get it to work. How do I cal it every load?
Jonny Wood
Can anyone help me implement Reigels solution? I can't get it to work.
Jonny Wood
Finally got this to work, thanks for the solution Reigel!
Jonny Wood