David
David

Reputation: 4895

Scrolling up and down on full screen based webpage

Here is a Fiddle showing my problem : http://jsfiddle.net/jnyx3q67/

My webpage starts with a full screen introduction. What I want is :

Here is what I did, but it the scroll up doesn't work.

lastScrollTop = 0;

$(window).scroll(function(event){

    // st determines the direction of the scroll
    var st = $(this).scrollTop();

    // if scrolling down, and if scrollbar is at the very top of the document
    // then directly scroll to "div"
    if (st > lastScrollTop && document.body.scrollTop < 1000 ) {
        $('body').animate(
            {scrollTop: $("div").offset().top},
            1000
        );
    } 

    // if scrolling up, and if scrollbar is at the top of "div"
    // then directly scroll to the very top of the document
    else if(document.body.scrollTop <= 1000) {
        $('body').animate(
            {scrollTop: 0}, 
            1000
        );
    }
});

Upvotes: 1

Views: 1776

Answers (2)

Alvaro
Alvaro

Reputation: 41595

If you want to avoid problems, I would suggest you to use an already existent plugin rather than trying to reinvent the wheel.

fullPage.js would be a good choice for it.

When you start worrying about other factors such as old browsers compatibility, Apple trackpad scrollings, touch detection, performance (css3 transforms), touch screen computers compatibility, anchors in the URL, callbacks and so on... then is when you realize it needs much more work than what you though at first.

You can use fullPage.js with a scrolling bar by using the option scrollBar:true as you can see in this example.

Upvotes: 1

CoƆ
CoƆ

Reputation: 11

The main problem here is that every time a scroll event is detected, the function fires. This includes the scrolling caused by the animation itself.

Simple solution would be to add some blocking to the if condition to ensure it doesn't trigger the if condition again until the animation is complete.

var lastScrollTop = 0;
var blocking = 0;

$(window).scroll(function (event) {

    var st = $(this).scrollTop();

    if (blocking == 0 && st > lastScrollTop) {
        blocking = 1;
        $('body').animate({
            scrollTop: $("div").offset().top
        },
        1000,
        function () {
            lastScrollTop = $(this).scrollTop();
            blocking = 0;
        });

    } else if (blocking == 0 && st < lastScrollTop) {
        blocking = 1;
        $('body').animate({
            scrollTop: 0
        },
        1000,
        function () {
            lastScrollTop = $(this).scrollTop();
            blocking = 0;
        });
    }

});

Fiddle: http://jsfiddle.net/z7es327j/

Upvotes: 1

Related Questions