[Tips & Trick] Smooth scroll to Top of Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
#1
Code:
<body id="top">

Code:
<a href="#top" onclick="scrollToTop();return false">Back to Top &uarr;</a>

Code:
function scrollToTop() {
    var position =
        document.body.scrollTop || document.documentElement.scrollTop;
    if (position) {
        window.scrollBy(0, -Math.max(1, Math.floor(position / 10)));
        scrollAnimation = setTimeout("scrollToTop()", 30);
    } else clearTimeout(scrollAnimation);
}

If you need a plain JavaScript function to add a smooth scrolling back to the top of the page, you can use this script.

Add an id of "top" to the <body> tag. Like this: <body id="top">
Add the onclick function to the link. Like this: <a href="#top" onclick="scrollToTop(); return false">Back to Top ↑</a>
Then either:
Include the JavaScript function in your markup, preferrably at the bottom before the closing </body> tag if possible.
Or, create a JavaScript file, place the script in it and call that file from your HTML document (either from the </head> section, or before the closing </body> tag if possible.)
Since this script is not part of the UI it can load last and will not negatively affect the user experience or usability of the page.

demo : You are not allowed to view links. Register or Login to view.

You are not allowed to view links. Register or Login to view.
Tuhan Yesus itu baik  Angel
Reply
#1
Code:
<body id="top">

Code:
<a href="#top" onclick="scrollToTop();return false">Back to Top &uarr;</a>

Code:
function scrollToTop() {
    var position =
        document.body.scrollTop || document.documentElement.scrollTop;
    if (position) {
        window.scrollBy(0, -Math.max(1, Math.floor(position / 10)));
        scrollAnimation = setTimeout("scrollToTop()", 30);
    } else clearTimeout(scrollAnimation);
}

If you need a plain JavaScript function to add a smooth scrolling back to the top of the page, you can use this script.

Add an id of "top" to the <body> tag. Like this: <body id="top">
Add the onclick function to the link. Like this: <a href="#top" onclick="scrollToTop(); return false">Back to Top ↑</a>
Then either:
Include the JavaScript function in your markup, preferrably at the bottom before the closing </body> tag if possible.
Or, create a JavaScript file, place the script in it and call that file from your HTML document (either from the </head> section, or before the closing </body> tag if possible.)
Since this script is not part of the UI it can load last and will not negatively affect the user experience or usability of the page.

demo : You are not allowed to view links. Register or Login to view.

You are not allowed to view links. Register or Login to view.
Tuhan Yesus itu baik  Angel
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)