Home >Web Front-end >JS Tutorial >How to Create a Browser-Agnostic Scroll to Top Animation with Pure JavaScript?
Browser-Agnostic Scroll to Top Animation
When faced with the task of creating a simple "scroll to top" animation for a link, it's tempting to reach for a JavaScript library like jQuery or MooTools. However, it is possible to achieve this effect with pure JavaScript, ensuring cross-browser compatibility.
The provided code implements a scroll animation that gracefully slides the document back to the top over a specified duration. It is a standalone function that can be applied to any element with a scroll bar, providing a better user experience by allowing them to quickly return to the top of the page.
<code class="javascript">function scrollTo(element, to, duration) {</code>
In the provided HTML snippet, a button with the ID "scrollme" is used as the trigger for the animation:
<code class="javascript">function runScroll() { scrollTo(document.body, 0, 600); } var scrollme; scrollme = document.querySelector("#scrollme"); scrollme.addEventListener("click",runScroll,false)</code>
The above is the detailed content of How to Create a Browser-Agnostic Scroll to Top Animation with Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!