user1374796
user1374796

Reputation: 1582

jQuery: animate scroll to next only working once

I have a simple jQuery function whereby clicking on each instance of .load-more will fade in the next instance of .inside and scroll to it. The first .load-more click works fine, scrolls you down to .inside successfully, but then clicking on the next .load-more fades in the next instance of .inside but is for some reason not scrolling to it, not too sure why?

jsFiddle demo: http://jsfiddle.net/neal_fletcher/K9nMS/5/

jQuery:

$(document).ready(function () {

    var divs = $(".wrap > .div");
    for (var i = 0; i < divs.length; i += 3) {
        divs.slice(i, i + 3).wrapAll("<div class='inside'><div class='new'></div></div>");
    }

});


$(document).ready(function () {

    Resize();
});

$(window).resize(function () {
    Resize();
});

function Resize() {
    var windowHeight = $(window).height() + 'px';
    $('.inside').css('height', windowHeight);
}


$(document).ready(function () {

    $(".new .div:last-child").after("<span class='load-more'>More?</span>");
    $('.inside').hide().filter(":first-child").show();

    $('.load-more').click(function () {
        var nextinside = $(this).parent().parent('.inside').nextAll(".inside:first"),
            nextloadmore = $(this).nextAll(".load-more:first");
        $(this).hide();
        nextinside.fadeIn();
        nextloadmore.fadeIn();
        $('.wrap').animate({
            scrollTop: nextinside.offset().top - 0
        }, 700);
    });
});

Any suggestions or solutions would be greatly appreciated!

Upvotes: 1

Views: 986

Answers (1)

Faust
Faust

Reputation: 15404

You need to change the position for scrolltop for each successive set as a multiple of the set index:

scrollTop: nextinside.index() * nextinside.offset().top

I have it working for you here: http://jsfiddle.net/K9nMS/7/

Upvotes: 1

Related Questions