rebz rebz - 3 months ago 6x
jQuery Question

Using jQuery to find current visible element and update navigation

First time user here. I am usually capable of finding answers for questions but I am having a difficult time figuring this one out.

The Goal:

I have a single page layout with a sidebar navigation that when clicked will scroll down to an element on the page. However, if the user just scrolls down the page to a specific element

I want the corresponding link in the navigation to become
. The navigation link and the corresponding element share the same value via

Similar to:

HTML Example below:

<a name="value">Link</a>

<section id="value">
content goes here

Obviously, there's more sections, links, elements, etc. But this is the gist of it. So when the user scrolls down to
will have gained the class active.

I found an answer on here earlier that has helped somewhat but I am still having some issues. See this link for more information.

Current Javascript/jQuery:

$(document).scroll(function() {
var cutoff = $(window).scrollTop();
var cutoffRange = cutoff + 200;

// Find current section and highlight nav menu
var curSec = $.find('.current');
var curID = $(curSec).attr('id');
var curNav = $.find('a[name='+curID+']');

if ($(this).offset().top > cutoff && $(this).offset().top < cutoffRange) {
return false; // stops the iteration after the first one on screen

The Problem:

While the above code works to an extent I am running into one big issue. I am having trouble getting an entire element to stay
. If the top of the element goes out of the window it will lose the class. I fixed that by adding a range for new elements, but now when the user scrolls upwards the previous element will not gain the class
until the top of the element reaches the top of the window. I would prefer it if a dominant portion of the window, when visible, gained the

Any help, ideas or suggestions would be greatly appreciated.

Thanks in advance!


It sounds like you want to check the bottom edge of the section and not the top. Try this and remove the range all together:

if($(this).offset().top + $(this).height() > cutoff){

EDIT: Created a fiddle. I think this is what you're describing.