I want to build a script for scrolling up/down to section tag of page. My source code looks like this:
HTML:
<div class="move">
<div class="previous">UP</div>
<div class="next">DOWN</div>
</div>
<section>First</section>
<section>Second</section>
<section>Third</section>
<section>Fourth</section>
CSS:
section{
height: 400px;
border: 1px solid black;
}
.move{
position: fixed;
bottom: 0;
right: 0;
}
I also have two buttons which are fixed at the bottom of the page.
Now I want to make a script for scroll up/down to sections. What if somebody refresh web page in situation - for example section 2 will be at the top of the page? How to determine which section is currently nearest top of the page?
Here is fiddle.
The following example uses the current scroll position of the page to determine which section element needs to be scrolled to rather than an explicit variable, which would become out of sync if the user were to manually scroll to a different section then press the nav buttons.
$(function() {
var $window = $(window);
$('.next').on('click', function(){
$('section').each(function() {
var pos = $(this).offset().top;
if ($window.scrollTop() < pos) {
$('html, body').animate({
scrollTop: pos
}, 1000);
return false;
}
});
});
$('.previous').click(function(){
$($('section').get().reverse()).each(function() {
var pos = $(this).offset().top;
if ($window.scrollTop() > pos) {
$('html, body').animate({
scrollTop: pos
}, 1000);
return false;
}
});
});
});
Working example: JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With