Create a Scroll that goes up and down Javascript

Asked

Viewed 746 times

1

Hello! I made one scroll with javascript. After clicking on a button he goes up and another he goes down. But I didn’t like to leave 2. I would like to use a single button to go to the top and another pro final.

The Code:

 $(document).ready(function(){
  $("#scroll").click(function(){
    $('html, body').animate({scrollTop:0}, 'slow');
    });
  
    
    $("#scroll").click(function(){
      $('html, body').animate({scrollTop:$(document).height()}, 2000);
      return false;
      });
      });

  • Do you want to do both actions with one button only ? The button goes to the top and then to the end ?

  • Yeah. I got it here.

1 answer

1


Test like this:

$(function () {
  let botao = $('button');
  
  botao.on('click', function () {
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
      $('html, body').animate({ scrollTop: 0 }, 2000, function () {
        botao.html('Descer');
      });
    } else {
      $('html, body').animate({ scrollTop: $(document).height() - $(window).height() }, 2000, function () {
        botao.html('Subir');
      });
    }
  });
});
button
{
  position: fixed;
  right: 15px;
  bottom: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button">Descer</button>

<!-- <br> só p/ criar a rolagem na página -->
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>
<br><br><br><br><br><br>

Browser other questions tagged

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