Wosley Alarico Wosley Alarico - 3 months ago 11
CSS Question

How change the menu item to a different color according to its section using jquery

At the moment,my navbar does the following using jquery on my WordPress site:
When I scroll at about 150 px,it gets fixed to the top

var num = 150; //number of pixels before modifying styles
$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {
$('nav#site-navigation').addClass('fixed');
} else {
$('nav#site-navigation').removeClass('fixed');
}
});


Then as I scroll down to about, the about menu item get highlighted...then as I scroll down to products section,the products and services menu item gets highlighted,the about dehighlihts and so forth.

$("nav ul li a").addClass("marker");
var navLinks = $('nav ul li a'),
navH = $('nav').height(),
section = $('section'),
documentEl = $(document);
documentEl.on('scroll', function() {
var currentScrollPos = documentEl.scrollTop();
section.each(function() {
var self = $(this);
if (self.offset().top < (currentScrollPos + navH ) && (currentScrollPos + navH) < (self.offset().top + self.outerHeight())) {
var targetClass = '.' +self.attr('class') + 'marker';
navLinks.removeClass('active');
$(targetClass).addClass('active');
}
});
});


Now, How can I make the color of each menu item be different at my preference?
Eg:

If I scroll down to about,it should change the menu item color to green.
enter image description here
For products and services, the menu item should be orange...and so forth for the others.
enter image description here

Answer

You can update your scrolling function like this:

$(window).bind('scroll', function () {
        if ($(window).scrollTop() > num) {
            $('nav#site-navigation').addClass('fixed');
            $("a.marker.active:contains(About)").addClass('item-2');        
            $("a.marker.active:contains(Products)").addClass('item-3');
            $("a.marker.active:contains(Scent)").addClass('item-4');
            $("a.marker.active:contains(Clients)").addClass('item-5');
            $("a.marker.active:contains(Contact)").addClass('item-6');
        } else {
            $('nav#site-navigation').removeClass('fixed');        
        }
    });   

In your stylesheet you can simply target each class that you added and play around with it. Eg:

a.marker.item-2.active {
    color: rgba(213, 221, 45, 0.6) !important;
}

Let me know if it does not work