Highlight active link when using scrollto based on current view

14,892

This should work for you to add the manual scrolling override:

$(function(){
    var sections = {},
        _height  = $(window).height(),
        i        = 0;

    // Grab positions of our sections 
    $('.section').each(function(){
        sections[this.name] = $(this).offset().top;
    });

    $(document).scroll(function(){
        var pos = $(this).scrollTop();

        // Look in the sections object and see if any section is viewable on the screen. 
        // If two are viewable, the lower one will be the active one. 
        for(i in sections){
            if(sections[i] > pos && sections[i] < pos + _height){
                $('a').removeClass('active');
                $('#nav_' + i).addClass('active');
            }  
        }
    });
});

Demo: http://jsfiddle.net/x3V6Y/

Share:
14,892
Michael
Author by

Michael

Updated on July 29, 2022

Comments

  • Michael
    Michael almost 2 years

    I have a website which is one page and the user navigates to each section using links which uses the scrollto jquery plugin.

    My problem is: I want to show the active link in the main menu. So if you scroll to the contact form the contact link is highlighted. Now I could do this in jquery by adding the class after clicking. If done like that if a user was to manually scroll to another section the contact link would still be active, which would be incorrect and misleading.

    So my thoughts would be to somehow work out which div id is currently in view. I don't really understand how to do that though. Any ideas?