Well ... not sure if you are still looking for an answer to your question, but I can make a suggestion ...
As already mentioned, you can use the scrollTop() method to determine which section is in the viewport. Here is a quick function that I put together to determine this, it cannot be optimized (I'm not a jQuery expert, sorry), but it seems to work and should at least put you on the right path to the solution:
function onScroll(event){ var scrollPos = $(document).scrollTop(); $('#menu-center a').each(function () { var currLink = $(this); var refElement = $(currLink.attr("href")); if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { currLink.addClass("active"); } else{ currLink.removeClass("active"); } }); }
This function basically takes the href each menu binding element and uses it to search for a <div> (or any other element if you want) with the corresponding identifier in the document. After that, it checks whether the top of this <div> above or at the current scroll position, and its bottom is still below the current scroll position. (These two conditions are true, meaning that this <div> is the highest in the viewport, so it should be considered as the active section.) Then the .active class is deleted / added. Of course, you can simply add / subtract values ββif you want to compensate when the section is considered βactiveβ.
It may be easier to just show what it does, so here's an updated JSFiddle with this feature. It is bound at first with $(document).on("scroll") - however, note that I also disabled it from the scroll event with $(document).off("scroll") while the scrolling is smooth, so the section does not change until you reach the destination section (if you click on one of the menu links). After performing a smooth scroll, I will bind the function to the scroll event again.
Anyway, I hope this is what you were looking for! If this is not the case, let me know and I will be happy to help further. (Or I'll try, at least, because, as I mentioned, jQuery is actually not my specialty ...) Good luck!
source share