Reputation: 1582
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?
Upvotes: 0
Views: 5437
Reputation: 144659
You can add classes to the a
elements and use next
and find
methods.
$(document).ready(function(){
$('a.className').on('click', function(e) {
e.preventDefault();
var offset = $(this).next().find('div').offset().top;
$('html, body').stop().animate({ scrollTop: offset }, 400);
});
});
You can also select the elements and cache the objects:
$(document).ready(function(){
var $a = $('a.className'), $targets = $('div.targets');
$a.on('click', function(e) {
e.preventDefault();
var i = $a.index(this);
var offset = $targets.eq(++i).offset().top;
$('html, body').stop().animate({ scrollTop: offset }, 400);
});
});
Upvotes: 2
Reputation: 688
Get the index of your div and slide to the next.
$(".linkToNextDiv").click(function(e)
{
var parent = $(this).parent("div");
var index = $(parent).index();
scrollToDiv(index+1);
});
This is just a generic example. You'll need to adapt it to your code.
Upvotes: -1