Scroll on the page adds the class "ACTIVE" to the menu

0

Hello, I'm having a hard time getting jquery to add an active class to the menu that is fixed at the top.

Anyone who wants to see the site to understand better follows the link.

Sapphire Site

I want the class to be added when I scroll on the page and are going through the section in question, if I am in the "Y" section, the menu becomes active in the "Y"     

asked by anonymous 28.05.2014 / 23:45

3 answers

4

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');
//    ^                     ^
    
29.05.2014 / 07:50
-1
$(a[href^='#']).click(function(){
$(nav navbar-nav menu a).removeClass('active');
$(this).addClass('active');
return false;


 });
    
29.05.2014 / 00:01
-1

You need to detect the click on your menu and add a class, in the active case, as quoted, for example:

$('#meuMenu ul li').click(function(){
    $('#meuMenu ul li').removeClass('active');    
    $(this).addClass('active');

});

JSFiddle

    
29.05.2014 / 00:03