How to make a "back to top" button on a page?

Asked

Viewed 21,331 times

2

How can I make a button return to top on an html page?

Jquery, javascript, which would be best?

2 answers

10

Using Jquery

//scroll normal
$('html,body').scrollTop(0);

//scroll suave
$('html, body').animate({scrollTop:0}, 'slow'); //slow, medium, fast

Using Javascript

var scrollTop = function() {
    window.scrollTo(0, 0);
};

8

The best way will depend on your needs.

In addition to the form presented by Mauro, you can use only html pointed to the href link to the page snippet at the top:

<span id='topo'></span>

<p>
  bla bla <br> bla bla <br> bla bla <br> 
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
  bla bla <br> bla bla <br> bla bla <br>
</p>

<a href='#topo'>Voltar ao topo</a>

  • 1

    +1 Clean and objective solution, and works even with JS off. It’s not part of the question, but if he wants animated scroll, have scripts for it without losing compatibility. Here’s one without jQuery: https://github.com/cferdinandi/smooth-scroll/blob/master/src/js/smooth-scroll.js and one with https://css-tricks.com/snippets/jquery/-smoothing/#comment-197181

Browser other questions tagged

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