4
    <div class="wrap">
        <div class="layer">
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
    <div class="post"></div>
        </div>
    </div>
<span class="next" style="cursor:pointer;"> (next div) </span>

jQuery with ScrollTo Plugin (http://demos.flesler.com/jquery/scrollTo/)

$('.next').click(function() {
    $(".wrap").scrollTo( $('.post').next(), 800, {margin:true} );
});

Demo : http://jsfiddle.net/UaGjs/8/

It doesnt work :( It work only 1st time

Jonas
  • 121,568
  • 97
  • 310
  • 388
l2aelba
  • 21,591
  • 22
  • 102
  • 138

4 Answers4

9

Working on Tomalak's answer you need to update the reference obj points to to the next element

http://jsfiddle.net/UaGjs/7/

var next;
$('.next').click(function() {
   if ( next === undefined ) {
     next = $('.post').next();
   } else {
      next = next.next();   
   }
   $(".wrap").scrollTo(next , 800, {margin:true} );
});

I've updated it with Prev but it can be improved to remove the duplication

http://jsfiddle.net/UaGjs/10/

I've noticed there is an occompanying plugin called Serial Scroll

Final edit

http://jsfiddle.net/nickywaites/UaGjs/13/

Nicky Waites
  • 2,428
  • 18
  • 19
1

Because you always re-obtain a handle to the DOM elements with $('.post'), rather than re-using the object and calling .next() on it iteratively.

Try the following. It's untested and rough/ready, but should demonstrate how you can get around the scoping issue.

$(function() {
    var $obj = $('post');
    $('.next').click(function() {
        $('.wrap').scrollTo($obj.next(), 800, { margin:true });
    });
});
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

Because you always re-obtain a handle to the DOM elements with $('.post'), rather than re-using the object and calling .next() on it iteratively.

Try the following. It's untested and rough/ready, but should demonstrate how you can get around the scoping issue.

Mark Ursino
  • 31,209
  • 11
  • 51
  • 83
  • add this $(function() { var $obj = $('post'); $('.next').click(function() { $('.wrap').scrollTo($obj.next(), 800, { margin:true }); }); }); – Mayank Jindal Mar 04 '12 at 10:15
0

I didn't have much luck working with next(). What I did was load all my elements of the same class into an array:

 myArray = $('.post');

Then initialize an index:

 index = 1;

Then iterate through the array:

$('.next').click(function() {
 $(".wrap").scrollTo( myArray[index], 800, {margin:true} );
 index++;
});

Hope this is helpful!

LauraNMS
  • 2,720
  • 7
  • 39
  • 73