Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll up/down to sections with fixed buttons

Tags:

html

jquery

css

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.

like image 249
repincln Avatar asked Mar 23 '23 00:03

repincln


1 Answers

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

like image 156
Chris Pickford Avatar answered Apr 02 '23 02:04

Chris Pickford