Remove class on body does not work with pagepiling.js

640 Views Asked by At

I've made a website using pagepiling.js, this script adds the class 'active' on the section which is in the viewport. Now I want add a class on my body when my section1 is active like this:

$(document).ready(function() {
    if ($('#section1').hasClass("active") === true) {
        $('body').toggleClass("one");
    }
});

It is working well (the class is added on the body) but when I scroll my section1 does not have the class active because I am now on section2, the class on the body is not removed. How can I fix it? I also tried:

$(document).ready(function() {
    if ($('#section1').hasClass('active')) {
        $('body').addClass('one');
    }
    else {
        $('body').removeClass('one');
    }
});

But it is not working.

2

There are 2 best solutions below

1
On

You have to put your condition inside scroll event because you should check every time the user scroll :

$('body').on('scroll', function() {
    if ( $('#section1').hasClass("active") ){
        $('body').toggleClass("one");
    }
});

Hope this helps.

0
On

Now I want add a class on my body when my section1 is active

You actually don't need to.

PagePiling.js adds a class to the body element for you with the form pp-viewing-page2. You can check it in your DOM inspector in the demo page.

But if you still want to add a class, just use the callbacks the plugin provides, like this:

$('#pagepiling').pagepiling({
    afterLoad: function(anchorLink, index){
        if(index == 1){
            $('body').addClass('one');
        }else{
            $('body').removeClass('one');
        }           
    }
});