Here is a suggestion:
Explanation:
- creates a function
addClass
to assign the class to the li
from the right menu
- cache the
li
's of the menu and the positions of each section
, as well as each element section
- listen to the event
scroll
and find the corresponding menu item (i
) at last section
which have the position below the scroll
(namely: the scroll
have passed through it). Here (if (scroll > this)
) can adjust with a numeric value for if to fire sooner or later. For example: if (scroll > this - 100)
will assign the class a little earlier.
- listen to the click also and add corresponding class
jQuery / Javascript
function addClass(el) {
menu.removeClass('active');
$(el).addClass('active');
};
var menu = $('#meuMenu .nav li');
var sectionPositions = $('section').map(function(){
return $(this).position().top;
});
var sections = $('section');
$(document).on('scroll', function () {
var scroll = $(document).scrollTop();
var currentElement;
$(sectionPositions).each(function (i) {
if (scroll > this - 50) currentElement = menu[i];
});
currentElement && addClass(currentElement);
});
menu.on('click', function () {
addClass(this);
});
Now you just need to add to CSS (or use what you already have):
.active{
border: 1px green solid; # ou outra propriedade que goste
}
You can also change the CSS directly in the element, thus using:
function addClass(el) {
menu.find('a').css('color', 'inherit');
$(el).find('a').css('color', 'blue');
};
Note: You have an error at line 129 of the index file:
Change:
$(nav navbar-nav menu a).removeClass('active');
for the code below (with quotation marks):
$('nav navbar-nav menu a').removeClass('active');
// ^ ^
Perfect Would like to know now how I do to take the class back to the top of the page.
– manzetti.denis
@Manzetti.Nis, when? What should be the cause that makes taking the class and going to the top again? Can you explain better?
– Sergio