Using jQuery to find current visible element and update navigation

rebz picture rebz · Jul 27, 2011 · Viewed 12.5k times · Source

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 #id I want the corresponding link in the navigation to become .active. The navigation link and the corresponding element share the same value via element#id and a[name].

Similar to: NikeBetterWorld.com

HTML Example below:

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

<section id="value">
    content goes here
</section>

Obviously, there's more sections, links, elements, etc. But this is the gist of it. So when the user scrolls down to section#value the a[value] 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+']');
    $(curNav).addClass('active');

    $('.section').each(function(){
        if ($(this).offset().top > cutoff && $(this).offset().top < cutoffRange) {
            $('.section').removeClass('current')
            $(this).addClass('current');
            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 .current. 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 .current 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 .current class.

Any help, ideas or suggestions would be greatly appreciated.

Thanks in advance!

Answer

James Montagne picture James Montagne · Jul 27, 2011

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.

http://jsfiddle.net/pdzTW/