John the Painter
John the Painter

Reputation: 2615

jQuery/JS – scroll to next element on click (scrollable div issues)

I have a simple blog, and each blog post has a number of images ranging from 1 to 10. If you click on any of the images in the post, it should scroll you down to the next post. I thought something as simple as this would've worked:

$('.each-journal-entry .slider-container .journal-slider .each-slide img').on('click', function () {
    var $this = $(this);
    $('.journal-container').animate({
        scrollTop: $this.closest('.each-journal-entry').next().offset().top
    }, 500);
});

But when I click another image, except for the first one, it just scrolls to an odd position.

I managed to achieve this with some help, and you can see the output here: http://jsfiddle.net/w7rtcmp0/3/ which works great, but the difference for me is that my content is in a scrollable div (hence .journal-container and not html, body.

Any ideas why I am having this issue? I have created a jsFiddle with the scrollable div, and if you click an image further down... it replicates this issue... so hopefully this helps.

http://jsfiddle.net/w7rtcmp0/5/

Thanks.

Upvotes: 0

Views: 684

Answers (3)

dekajoo
dekajoo

Reputation: 2102

You may want to look at Ariel Flesler's jQuery scrollTo plugin, I had the same issue and using this saved me hours of debugging.

Upvotes: 0

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

jQuery adjusts offset().top() based on the current scroll position.

Using JavaScript's offsetTop property should fix the problem:

scrollTop: $this.closest('.each-journal-entry').next()[0].offsetTop

Fiddle: http://jsfiddle.net/m7cm5oL6/

Upvotes: 2

Andrew Ice
Andrew Ice

Reputation: 841

So I think you were trying to use the wrong height.

Here I set a variable of height and set it to the height of the current journal/blog object. This allows me to scroll my height all the way down to the next available blog object.

http://jsfiddle.net/w7rtcmp0/24/

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

  $('.scrollable').animate({
    scrollTop: height
  }, 2000);
});

Upvotes: 0

Related Questions