javascriptjqueryiscroll

Add class to current page using iScroll


As the title suggests, I'm trying to add a class to the current 'snapped-to' element. With this:

var verticalScroll;
verticalScroll = new IScroll('#wrapper', {
    snap: true
});
verticalScroll.on('scrollEnd', function(){
    alert(this.currentPage);
});

I get this alert when the scrolling is done:

[object Object]

So I was thinking I could use something like this to add a class:

verticalScroll.on('scrollEnd', function(){
    var newPage = this.currentPage;
    $(newPage).addClass('current');
});

But no joy. Done lots of searches to try and find the same situation. It must be something fairly simple.


Solution

  • Yeah, it's a little bit tricky. Some time ago I tried to add an "active" class to the link and the page. I ended up with this:

    after scroll ended:

    myScroll.on('scrollEnd', function () {
        addActiveClass();
    });
    

    the function:

    function addActiveClass() {
    
        // get current page with iScroll
        var currentSection = myScroll.currentPage.pageY;
    
        // get current link and page
        var activeLink = $('nav a[href="' + currentSection + '"] span');
        var activeSection = $('section[class="' + currentSection + '"]');
    
        // remove active class from all links and pages
        $('nav a span, section').removeClass('active');
    
        // add active class to current link and page
        $(activeLink).addClass('active');
        $(activeSection).addClass('active');
    }
    

    Only one thing that annoys me, you have to give every section a page number as a class:

    <section class="0"> … <section>
    <section class="1"> … <section>
    <section class="2"> … <section>
    

    Same with links:

    <a href="0"></a>
    <a href="1"></a>
    <a href="2"></a>
    

    But maybe could be added dynamically somehow.

    And don't forget option:

    snap: 'section'
    

    jsfiddle demo