Skip to content Skip to sidebar Skip to footer

Scroll To Next And Previous Div Using Scrolltop, How Do I Accomplish This?

I'm currently designing a mobile-first survey website and I can't quite figure out how to scroll the the next and previous div using jQuery. Every div is supposed to be a question

Solution 1:

I fixed few things in your code to fix it.

Demo:http://jsfiddle.net/aamir/Da3qp/4/

(function() {
    var scrollTo = function(element) {
        console.log(element);
        $('html, body').animate({
            scrollTop: element.offset().top
        }, 500);
    }

    $('.next').click(function(event) {
        event.preventDefault();
        var$current = $('#container > .question-container.current');
        var$next = $current.next().first();
        if ($next.length!=0) {
            $current.removeClass('current')
            $next.addClass('current');
            scrollTo($next);
        }
    });
    //don't use $('.back') since there are two and the event will be triggered twice
    $('#back').click(function(event) {
        event.preventDefault();
        var$current = $('#container > .question-container.current');
        var$prev = $current.prev().first();
        if ($prev.length!=0) {
            $current.removeClass('current')
            $prev.addClass('current');
            scrollTo($prev);
        }
    });
})();

Post a Comment for "Scroll To Next And Previous Div Using Scrolltop, How Do I Accomplish This?"