I’m currently using the smooth scrolling technique to scroll from div to div, basically I have a whole load of divs, one after the other, when you click on the current div it takes you to the next one etc.
But that’s where I’m having a problem, as currently I have to set the # for each div to tell it to go to the next. Here’s my code, it might make a bit more sense:
HTML:
<a href="#slide-2"><div id="slide-1" class="slides">
<div class="text">
ONE
</div>
</div></a>
<a href="#slide-3"><div id="slide-2" class="slides">
<div class="text">
TWO
</div>
</div></a>
<a href="#slide-4"><div id="slide-3" class="slides">
<div class="text">
THREE
</div>
</div></a>
<a href="#slide-5"><div id="slide-4" class="slides">
<div class="text">
FOUR
</div>
</div></a>
<a href="#slide-6"><div id="slide-5" class="slides">
<div class="text">
FIVE
</div>
</div></a>
<a href="#slide-7"><div id="slide-6" class="slides">
<div class="text">
SIX
</div>
</div></a>
jQuery:
$(document).ready(function(){
$('a[href*=#]').bind('click', function(e) {
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump
var target = $(this).attr("href"); //Get the target
// perform animated scrolling by getting top-position of target-element and set it as scroll target
$('html, body').stop().animate({ scrollTop: $(target).offset().top }, 400, function() {
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
return false;
});
});
As you can see, the href for slide-1 takes you to slide-2, and so on, but there will be quite a lot of divs in the end, with more being added as and when, so I was wondering if there was a simpler way of scrolling from div to div, i.e. Is there a way of detecting the next div and scrolling to it and so on?
You can add classes to the
aelements and usenextandfindmethods.You can also select the elements and cache the objects: