Here's a suggestion:
Explanation:
- creates a
addClass
function to assign the class to li
of the right menu
- Cache the
li
's from the menu and the positions of each section
, as well as each section
- listen for the event
scroll
and look for the menu element that corresponds ( i
) to the last section
that have the position lower than the scroll
(ie scroll
has passed through it). Here ( if (scroll > this)
) can adjust with a numerical value so that if triggered sooner or later. For example: if (scroll > this - 100)
will assign the class a little earlier.
- listen for the click also and add matching 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 only need to add in 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, using:
function addClass(el) {
menu.find('a').css('color', 'inherit');
$(el).find('a').css('color', 'blue');
};
Note: You have an error on 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');
// ^ ^