FullPage.js - add active class to menu anchor when on a nonematching section

Selo picture Selo · Mar 6, 2014 · Viewed 10k times · Source

Okay, the title might be a bit hard to understand, I'll try and explain.

So I'm using fullpage.js

I have in total 9 sections: Home About(about has 6 "undersections" that is a continuation of the first about section) Contact

In the menu there are only 3 navigation options Home, about, contact. I've made the menu so that the active class is added when on corresponding section - as simply done with ready made options. When I scroll and leave the first about section the active class is remove and the menu item is not highlighted. So here's the thing I want the active class to remain on all the "undersections" of about. So the menu item "About" is highlighted until the contact section.

I thought I'd make it work with some "outside" JS so depending on the url the class would be added to the anchor with id "all-about":

$(document).ready(function () {
            if (location.href.match(/#about1/ig) || location.href.match(/#about2/ig)){
                $('#all-about').addClass('active');
            }
        });

This does not work. What in the fullpage JS would I change or how to change my code to work?

Thanks!

Answer

Alvaro picture Alvaro · Mar 6, 2014

I would make use of the plugin callbacks to achieve that.

You could make use of afterLoad with something like this:

$.fn.fullpage({
    slidesColor: ['red', 'blue'],
    afterLoad: function(anchor, index){
        var activeItem;

        if(index == 1 || index == 2 || index == 3){
            activeItem = $('#menu').find('li').first()
        }else{
             activeItem = $('#menu').find('li').last()    
        }

        activeItem
            .addClass('active')
            .siblings().removeClass('active');
    }
});

Note that I'm not using the menu option anymore to handle the active class as I wish.

Live example