Reputation: 157
I'm trying to make a bar on top of my page which scrolls to the next element every time you click the button in the current element.
My code looks like this:
<div id="wrap">
<div class="section">
Click here!
<button class="nav" type="button">Go!</button>
</div>
<div class="section">
<button class="nav" type="button">Next!</button>
</div>
<div class="section">
<button class="nav" type="button">Done!</button>
</div>
</div>
jQuery:
$('button.nav').click(function() {
$('#wrap').animate({
scrollTop: $(this).parent().next().offset().top
}, 400);
});
The problem: Instead of scrolling to the section with Done!, it does not scroll at all when I click Next!. The button Go! scrolls down correctly.
Upvotes: 1
Views: 377
Reputation: 1075337
Use position
rather than offset
and add in your current scrollTop
:
$('button.nav').click(function() {
var w = $("#wrap");
w.animate({
scrollTop: $(this).parent().next().position().top + w.prop("scrollTop")
}, 400);
});
$('button.nav').click(function() {
var w = $("#wrap");
w.animate({
scrollTop: $(this).parent().next().position().top + w.prop("scrollTop")
}, 400);
});
body,
html {
height: 100%;
margin: 0;
padding: 0;
}
.section {
height: 20em;
}
#wrap {
height: 100%;
overflow: scroll;
}
<div id="wrap">
<div class="section" id="a">
Click here!
<button class="nav" type="button">Go!</button>
</div>
<div class="section" id="b">
<button class="nav" type="button">Next!</button>
</div>
<div class="section" id="c">
<button class="nav" type="button">Done!</button>
</div>
<div style="height: 50em"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Here's a version that wraps back to the top:
$('button.nav').click(function() {
var w = $("#wrap");
var next = $(this).parent().next(".section");
var top = next.length ? next.position().top + w.prop("scrollTop") : 0;
w.animate({
scrollTop: top
}, 400);
});
body,
html {
height: 100%;
margin: 0;
padding: 0;
}
.section {
height: 20em;
}
#wrap {
height: 100%;
overflow: scroll;
}
<div id="wrap">
<div class="section" id="a">
Click here!
<button class="nav" type="button">Go!</button>
</div>
<div class="section" id="b">
<button class="nav" type="button">Next!</button>
</div>
<div class="section" id="c">
<button class="nav" type="button">Done!</button>
</div>
<div style="height: 50em"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 1