Home > Web Front-end > JS Tutorial > How to Create Smooth Animated Scrolling to Top Without jQuery?

How to Create Smooth Animated Scrolling to Top Without jQuery?

Barbara Streisand
Release: 2024-11-03 08:46:29
Original
597 people have browsed it

How to Create Smooth Animated Scrolling to Top Without jQuery?

Animated Scrolling to Top in Many Browsers (Excluding jQuery)

Implementing a smooth animated "scroll to top" effect on a web page is a common requirement. However, relying on external JavaScript libraries like jQuery can be undesirable. This article presents a cross-browser solution for creating such an animation without the need for additional frameworks.

Understanding the Script

The provided code involves a recursive function called scrollTo, which takes three parameters:

  1. element: The target element for scrolling (e.g., document.body)
  2. to: The desired scroll position (e.g., 0 for scrolling to the top)
  3. duration: The animation's duration in milliseconds

The function calculates the difference between the element's current scroll position and the desired one and applies a small increment to bridge the gap every 10 milliseconds. This creates a gradual and smooth scrolling effect.

Usage Example

To use this solution, simply include the JavaScript snippet provided in the answer and create a listener for the click event on the element you want to use to initiate scrolling. Here's an example:

<code class="html"><button id="scrollme" type="button">To the top</button></code>
Copy after login
<code class="javascript">var scrollme;
scrollme = document.querySelector("#scrollme");
scrollme.addEventListener("click",runScroll,false)

function runScroll() {
  scrollTo(document.body, 0, 600);
}</code>
Copy after login

The above is the detailed content of How to Create Smooth Animated Scrolling to Top Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template