Steggie Steggie - 3 years ago 74
CSS Question

Scroll past ID addClass to navigation menu to change currect class

I'm building a one page design website and would like to know how to add a class to my navigation menu items once I scroll past an ID.

I'm guessing it would be something like:

if at ID-X addClass .active to menuitem-y


In my navigation menu I have a link to prices (link is www.example.com/#prices). So when I click on Prices it smooth scrolls to the ID #prices.

So the could should look like:

if "#prices" addClass(.active)->Menuitem-y


I guess?

** Update **
Thanks to DaniP I've got some code that fires an alert when #prices is reached.

var target = $("#prices").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
alert("made it!");
clearInterval(interval);
}
}, 250);


Can I put CSS instead of the alert? like
#menuitem-y{color:#000;}


This works but only for one instance, what is the best way to apply this to more menu items?

var target = $("#prices").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
$("#menu-item-16 a").addClass("active-prices");
clearInterval(interval);
}
}, 250);

Answer Source

I've built a jquery plugin that sounds like it'd work for what you're doing here.

https://github.com/tferullo/eavesdrop

It adds a class to the navigation element as it corresponds to the element in view. Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download