00 Votes

jQuery: Scroll up smoothly on a webpage

Tip by Stefan Trost | 2012-07-13 at 22:13

Normally, we are using anchor links to provide our users to jump up or down within the same web page. If you click on such an anchor link, the page view directly jumps to the corresponding point. But you can design this a little bit nicer and smoother. For example with the following jQuery code:

$("html, body").animate({scrollTop:0}, 800);

If this JavaScript code is executed, the page view moves as if by magic softly and smoothly to the top. The last parameter (here it is set to 800) specifies the duration of the scrolling in milliseconds. The higher the value, the slower it is scrolled. You can - depending on your preference - specify a different value here.

Example

Let's have a look at the procedure in an example. On our website, we want to connect all the links we have marked with the class "totop" with our code.

Here is one of our links:

<a href="#" class="totop">Ganz nach oben scrollen</a>

And here is our jQuery-JavaScript code to attach the code to the links:

$(document).ready(function() {      
  $(".totop").click(function(){
    $("html, body").animate({scrollTop:0}, 800);
    return false;
  });    
});

With this, all elements of our pages having the class "totop" get the function assigned. The "return false" should not be forgotten, because this line ensures, that the default action (follow the link) is no longer running.

JavaScript is disabled?

Unfortunately, this process only works if the user has JavaScript enabled in his browser. How we can also give other users the ability to use the links, you can find out in this tip.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.