John the Painter
John the Painter

Reputation: 2615

jQuery/JS – click blog image scroll to next blog item

I have a journal/blog section on a site I am building, and I am trying to write some JS/jQuery that would allow on click of any image on each blog item, to smooth scroll down to the next blog item. If you are viewing a current blog item but can see an image from the previous blog item, and click that, it would take you to the top of that blog item.

I guess a lot of it would be to do with scroll position and view. If viewing current post and click, then scroll to next post. If you click an image of a previous or next post that is just in view, you go to that post.

This effect is pretty similar to this > http://www.morganstudio.co.uk/journal/ I have built a quick jsFiddle http://jsfiddle.net/qfmejz81/1/ to work from and used some of the code from that site to build what I felt would work but it doesn't seem to work 100% (it tends to scroll just down a bit on click, rather than to the next post)

// Journal click image to scroll
$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click', function() {
    var e = $(this).parents('.each-journal-entry');
    var t = e.offset().top;
    var n = e.height();
    var r = $(window).scrollTop();
    var i = $(window).height();
    var s = null;
    if (t + n / 2 < r) {
        s = e;
    } else if (t + n / 2 - 48 > r + i) {
        s = e;
    } else {
        s = e.nextAll('.each-journal-entry');
    }
    var o = s.offset().top;
    var u = s.height();
    var a = o - ($(window).height() - u) / 2;
    $('body').stop().animate({
        scrollTop: a
    }, 500);
});

Upvotes: 0

Views: 772

Answers (1)

marty
marty

Reputation: 484

Based on the structure of your images you will want get the parent of the image which is a div with the class each-slide. Then set the animate "scrolltop" property to the top of the next element.

$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click',        function () {
    $this = $(this);

    $('html, body').animate({
        scrollTop: $this.closest('.each-journal-entry').next().offset().top
    }, 2000);
});

http://jsfiddle.net/w7rtcmp0/3/

Upvotes: 1

Related Questions