3

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Thibaud
  • 396
  • 5
  • 23
  • Did you just downvoted my answer? Can I ask why? – Alvaro Jan 21 '16 at 11:16
  • In any case, I'm wondering how can you accept an answer that doesn't even work... the scroll event is not even being propagated when using pagePiling.js... And I'm telling you this as the creator of the plugin... – Alvaro Jan 21 '16 at 11:21

2 Answers2

1

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • That's not the way to do it.... [IT DOESN'T EVEN WORK](http://jsfiddle.net/hrrLvd2a/31/) because pagePiling.js doesn't fire the scroll event. You should be using the pagePiling.js callbacks, or as I suggested in my answer, use the class pagePling.js adds for you. **Definitely this should not be the accepted answer.** – Alvaro Jan 21 '16 at 10:14
0

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');
        }           
    }
});
Alvaro
  • 40,778
  • 30
  • 164
  • 336