How to automatically scroll to the top when viewing the page footer?

Asked

Viewed 1,334 times

6

I’m making a site, which has some animations, and when arriving at the bottom of the site for the first time, should trigger an event where the page goes back to the top, but in the following times (without reloading) the event will not happen again.

How could I do that?

HTML:

<header>
</header>
<div id="content">
    <div id="broca">
    </div>
</div>
<footer>    
</footer>

CSS:

header, footer{
display:block;
height:200px;
background:red;
width:100%;
}
#content{
    display:block;
    width:100%;
    height:1500px;
background:blue;
}
#broca{
    width:50px;
    height:0;
    background:#000;
}

Jquery:

$(function(){
$(window).scroll(function() {
        var $broca = $('#broca');
        var st = $(this).scrollTop();
        if (st > $broca.height()){
            $broca.clearQueue().animate({
                height: st } , 1000);
        }
        if( st == 0 ) {

        } else {
            $broca.show();
        }
    }).scroll();
})

Jsfiddle

2 answers

2

Here is your code:

$(document).ready(function(){
    var $documentHeight = $(document).height();
    var $windowHeight = $(window).height();
    var $scrollHeight = $documentHeight - $windowHeight;
    var $toBottom = false;

    $(window).scroll(function(){
        var $broca = $('#broca');

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

        if(st > $broca.height()){
            $broca.clearQueue().animate({height: st}, 1000);
        }

        if(st == $scrollHeight && $toBottom == false){
            $(this).scrollTop(0);
            $toBottom = true;
        }

        if(st != 0){
            $broca.show();
        }
        else{
            $broca.hide();
        }
    });
});

You can test here: Jsfiddle

  • Had wrong an operator, but solved already. If the answer solved your problem, please mark as answered my reply. Thank you.

1


Declare this variable before the function:

var counter = 0;

Add to that:

$(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
               if (counter == 0){
                   counter++;
               $("html, body").animate({ scrollTop: 0 }, "slow");
        }
    }
});

See better here: Jsfiddle

  • He wants when he goes to the dps footer the first time, not to go back to the top. And his code doesn’t do that.

  • Okay, now do it and lean

  • 1

    Thank you Rafael, that’s exactly what I needed. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.