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.
About the Author
You 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
jQuery: Scroll up and down with and without JavaScript
Tip | 0 Comments
jQuery: Scroll down smoothly on a webpage
Tip | 0 Comments
jQuery: CSS Stylesheet Switcher
Tutorial | 1 Comment
Windows Batch Script: Computer Shutdown
Tutorial | 2 Comments
jQuery: Load and Replace DIV Content with clicking Links
Tutorial | 0 Comments
Reload Images, CSS, JS and Web Pages despite Browser Cache
Tip | 2 Comments
CSS: Include CSS Stylesheets in HTML
Tutorial | 0 Comments
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.