---
title: "Animate Scroll to Top with JavaScript"  
description: "Animate Scroll to Top with JavaScript"  
author: "Anonymous User"  
published: 2021-07-20  
updated: 2023-11-28  
canonical: https://www.mindstick.com/forum/156573/animate-scroll-to-top-with-javascript  
category: "javascript"  
tags: ["javascript"]  
reading_time: 2 minutes  

---

# Animate Scroll to Top with JavaScript

How to Animate Scroll to Top in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript)?

## Replies

### Reply by Aryan Kumar

Certainly! You can use JavaScript to create a smooth scroll-to-top animation. Here's an example:

```plaintext
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scroll to Top Animation</title>
  <style>
    body {
      height: 1500px; /* Adding some height to enable scrolling */
    }
    #scrollToTopBtn {
      position: fixed;
      bottom: 20px;
      right: 20px;
      display: none;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <!-- Content goes here -->

  <button id="scrollToTopBtn" onclick="scrollToTop()">Scroll to Top</button>

  <script>
    // Show/hide scroll-to-top button based on scroll position
    window.onscroll = function() {
      showScrollToTopButton();
    };

    function showScrollToTopButton() {
      var scrollToTopBtn = document.getElementById("scrollToTopBtn");
      if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        scrollToTopBtn.style.display = "block";
      } else {
        scrollToTopBtn.style.display = "none";
      }
    }

    // Smooth scroll to top function
    function scrollToTop() {
      var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;

      if (currentScroll > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, currentScroll - currentScroll / 8);
      }
    }
  </script>

</body>
</html>
```

In this example:

- The button with the id **scrollToTopBtn** is initially hidden (**display: none**).
- The **showScrollToTopButton** function is used to show or hide the button based on the scroll position.
- The **scrollToTop** function is responsible for the smooth scroll animation. It uses the **window.requestAnimationFrame** method for a smoother animation effect.

Adjust the button styles and animation parameters as needed for your specific design preferences.


---

Original Source: https://www.mindstick.com/forum/156573/animate-scroll-to-top-with-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
