0

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);
Cœur
  • 32,421
  • 21
  • 173
  • 232
Steggie
  • 485
  • 6
  • 27
  • Have you tried the Bootstrap scrollspy? http://getbootstrap.com/javascript/#scrollspy – Rory McCrossan Jun 14 '16 at 15:11
  • I'm not using Bootstrap. I'm using http://materializecss.com. It has a scrollspy function. http://materializecss.com/scrollspy.html this will probably work the same. Ill have a go – Steggie Jun 14 '16 at 15:12
  • 1
    Have you tried something ? at least search and try with your code http://stackoverflow.com/questions/7182342/how-to-detect-when-the-user-has-scrolled-to-a-certain-area-on-the-page-using-jqu – DaniP Jun 14 '16 at 15:18
  • in your title, do you mean _current_ or _correct_ class? – Cœur Jul 26 '17 at 11:58

1 Answers1

1

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!

tfer77
  • 736
  • 1
  • 6
  • 15
  • Edit, sorry did not see the example folder! Thanks! – Steggie Jun 15 '16 at 10:23
  • Thanks this script does do what I want. But now i have to implement it in my code. I found an error in your script, in the files I downloaded it said: `;function` at the beginning this should be `!function` according to your demo page... – Steggie Jun 15 '16 at 11:20
  • glad it worked. The semi-colon before the function invocation is a safety net against concatenated scripts and/or other plugins which may not be closed properly. – tfer77 Jun 15 '16 at 13:27