Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight active link when using scrollto based on current view

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?

like image 853
Michael Avatar asked Dec 05 '11 23:12

Michael


People also ask

How do you highlight the current link in CSS?

The :active selector is used to select and style the active link. A link becomes active when you click on it. Tip: The :active selector can be used on all elements, not only links.

How do you highlight a link in Javascript?

You can do : $(". highlight").

How do I change the active links in scrolling?

to change the link style we can simply add a active to the classList of link. All this is done every time the page is scrolled. window. onscroll = () => { var current = ""; sections.


1 Answers

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/

like image 190
AlienWebguy Avatar answered Oct 10 '22 02:10

AlienWebguy