Highlight active link when using scrollto based on current view

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

My problem: I want to show the active link in the main menu. Therefore, if you go to the contact form, the contact link will be highlighted. Now I can do it in jquery by adding a class after clicking. If this is done, if the user must manually go to another section, the contact link will still be active, which will be incorrect and misleading.

So, my thoughts would have to somehow decide which div id is currently in view. I really don't understand how to do this. Any ideas?

+7
source share
1 answer

This should help you add manual scrolling:

$(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/

+19
source

All Articles