Pergunta

I wrote a fairly simple smooth scrolling function using jQuery mousewheel extension, and having no former experience with $.mousewheel I ran into a problem.

Basically, once south delta is called, I call an $.animate function using scrollTop to a class of .anchor

HTML (simplified for question):

<div id="static-section" class="anchor"></div> <!-- width: 100%; height: 258px -->
<div id="alt-section" class="anchor"></div> <!-- width: 100%; height: 346px -->

jQuery:

$(document).ready(function() {
    $("body").mousewheel(function(event, delta, deltaX, deltaY) {
        if( delta > 0 ) {
            console.log("North: " + delta);
        }

        else if( delta < 0 ) {
            console.log("South: " + delta);
            // ANIMATE TO ANCHOR FUNCTION
            $("html,body").animate({scrollTop: $(".anchor").offset().top}, "slow");
        }

        return false;
    });
});

So: my problem is that it only animates to the first instance of .anchor (which would be #static-section) I have tried doing scrollTop: $(".anchor").next().top which obviously doesn't work, though no errors appear, it still only animates to the first instance. My first guess was to use a for loop, and I tried it, but it didn't work (no errors on that either.) I've never really had a use for for loops before, so I'm unsure as to whether or not what I did was correct. Any help would be much appreciated!

Note: jsFiddle (with the same code as my website) does not portray the same thing that I've already accomplished, so no live demo available. If you guys need it, I'll provide the URL upon request. :-)

Foi útil?

Solução

Something like this will step through the .anchor tags:

$(document).ready(function() {
    var $anchor = $('.anchor');
    $("body").mousewheel(function(event, delta, deltaX, deltaY) {
        if( delta > 0 ) {
            console.log("North: " + delta);
        }

        else if( delta < 0 ) {
            console.log("South: " + delta);
            // ANIMATE TO ANCHOR FUNCTION
            $("html,body").animate({scrollTop: $anchor.offset().top}, "slow");
            $anchor = $anchor.next('.anchor');
        }

        return false;
    });
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top