SoFunction
Updated on 2025-04-08

Detailed explanation of how JavaScript implements web pages to bring animations back to the top

The server was changed from Alibaba Cloud to Tencent Cloud. My code was always hosted on git before, but when I moved, I might be anxious. Some newly added files were not hosted on git before, so I lost them.

But it doesn't matter, you can rewrite it.

The previous blog back to the top feature was written by a previous front-end colleague, and I plan to try it myself this time.

Returning to the top is nothing more than an anchor point.

The first version:

<body style="height:2000px;">
    <div ></div>
    &lt;a href="#topAnchor" rel="external nofollow" style="position:fixed;right:0;bottom:0">Back to top</a>&lt;/body&gt;

This is useless js. I tried it simply using anchor points, it is easy to use.

It is easy to use, but the user experience is not very good, so I go back to the top in a moment. not good.

I don't like using jquery very much, and I like to use native no matter what I sit on, so I wrote an animation here in native JavaScript, probably that's it.

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Back to top&lt;/title&gt;
    &lt;style type="text/css"&gt;
        *{
            margin: 0;
            padding: 0;
        }
        body{
            height: 2000px;
            width: 100%;
        }
        .to_top{
            width: 60px;
            height: 60px;
            bottom: 10%;
            right: 20px;
            font-size: 40px;
            line-height: 70px;
            border: none;
            background: rgba(0,0,0,0.2);
            cursor: pointer;
            opacity: 0;
            transition: all 1s;
            /*Make the front point label always on the top level*/
            position: fixed;
            z-index: 99999;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class="to_top"&gt;
        &lt;img src="/uploads/gotop/" alt="" width="70;"&gt;
    &lt;/div&gt;
    &lt;script type="text/javascript"&gt;
         = function(){
            var timer = null;//Time identifier            var isTop = true;
            
            var obtn = ('to_top')[0];
             = function(){
                // Set the timer                timer = setInterval(function(){
                    var osTop =  || ;
                    //Reduced speed                    var isSpeed = (-osTop/6);
                     =  = osTop+isSpeed; 
                    //Judge, then clear the timer                    if (osTop == 0) {
                        clearInterval(timer);
                    } 
                    isTop = true;//Added in the event timer                },30);                          
            };
            //Get the visible window height of the page            var client_height =  || ;

            //Add judgment when scrolling, if you forget, it is easy to make mistakes            var osTop =  || ;
            if (osTop &gt;= client_height) {
                 = '1';
                }else{
                     = '0';
                }         
                if(!isTop){
                    clearInterval(timer);
                }
                isTop = false;
            
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

The above code can be placed in the html file and can be run directly.

The specific meaning of the code is basically commented.

If you don’t understand something, please Baidu on your own.

Method supplement

Method 1

//Triggered after the page loads = function(){
  var btn = ('btn');
  var timer = null;
  var isTop = true;
  //Get the page viewing area height  var clientHeight = ;

  
  // Triggered when scrolling   = function() {
  //Show back to top button    var osTop =  || ;
    if (osTop &gt;= clientHeight) {
       = "block";
    } else {
       = "none";
    };
  //In the process of going back to the top, the user scrolls the scrollbar and stops the timer    if (!isTop) {
      clearInterval(timer);
    };
    isTop = false;

  };

   = function() {
    //Set the timer    timer = setInterval(function(){
      //Get the scroll bar from the top height      var osTop =  || ;
      var ispeed = (-osTop / 7);
      
       =  = osTop+ispeed;
      //Get the top and clear the timer      if (osTop == 0) {
        clearInterval(timer);
      };
      isTop = true;
      
    },30);
  };
};

Method 2

&lt;!DOCTYPE html&gt;
 &lt;html lang="en"&gt;
 &lt;head&gt;
     &lt;meta charset="UTF-8"&gt;
     &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
     &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt;
     &lt;title&gt;Return to top effect&lt;/title&gt;
     &lt;style&gt;
         .slider-bar {
             position: absolute;
             left: 47%;
             top: 300px;
             margin-left: 600px;
              45px;
             height: 130px;
             background-color: pink;
             cursor: pointer;
         }
         .w {
              1100px;
             margin: 10px auto;
         }
         .header {
             height: 150px;
             background-color: purple;
         }
         .banner {
             height: 250px;
             background-color: skyblue;
         }
         .main {
             height: 1000px;
             background-color: yellowgreen;
         }
         span {
             display: none;
             position: absolute;
             bottom: 0;
         }
     &lt;/style&gt;
 &lt;/head&gt;
 &lt;body&gt;
     &lt;div class="slider-bar"&gt;
         &lt;span class="goBack"&gt;Back to top&lt;/span&gt;
     &lt;/div&gt;
     &lt;div class="header w"&gt;Head area&lt;/div&gt;
     &lt;div class="banner w"&gt;bannerarea&lt;/div&gt;
     &lt;div class="main w"&gt;Main part&lt;/div&gt;
 
     &lt;script&gt;
         // The querySelector() method returns the first element that matches the specified selector(), and the passed string must be         var sliderbar = ('.slider-bar');
         var banner = ('.banner');
         var bannerTop = ; // The length of the banner module from the top         var sliderbarTop =  - bannerTop; // The length from the top after the sidebar is fixed 
         var main = ('.main');
         var goBack = ('.goBack');
         var mainTop = ;  // The length of main module from the top         
         // Scroll is executed when a scroll event occurs         ('scroll', function() {
             if( &gt;= bannerTop) {    // The distance when the screen is rolled up                  = 'fixed';   // Turn the sidebar into a fixed state when the user scrolls to the banner module                  = sliderbarTop + 'px'; 
             } else {
                  = 'absolute';
                  = '300px';
             }
             
             if( &gt;= mainTop) {    // When the user scrolls to the main module, the return to top button is displayed                  = 'block';
             } else {
                  = 'none';
             }
             
         });
         ('click', function() {
             animate(window, 0);
         })
 
         /* Animation function:
           * obj Animation object (here refers to window)
           * target target position (top)
           * callback callback function (if there is no parameter transmission, it will not be executed)
           */
         function animate(obj, target, callback) {
             clearInterval();  // Clear the timer first to ensure that only one timer is executing to avoid bugs              = setInterval(function() {
                 // The distance from the top (negative)                 var step = (target - ) / 10;  // step step (slide up gradually with the page speed)                 step = step &gt; 0 ? (step) : (step); // step is not always an integer.  Round upwards greater than zero, round downwards less than zero                 if( == target) {  // Clear the timer after the page returns to the top (that is, the animation is completed)                     clearInterval();
                     // Determine whether the callback function has been passed                     /* if(callback) { 
                         callback();
                     } */
                     // It can be abbreviated as the following.  && is a short-circuit operator. Callback() will continue to be executed when there is callback (that is, the first expression is true).                     callback &amp;&amp; callback();
                 }
                 // (x, y) Scroll to a specific location of the document                 (0,  + step);
             }, 15);
         }
     &lt;/script&gt;
 &lt;/body&gt;
 &lt;/html&gt;

This is the article about this detailed explanation of how JavaScript implements web animations to return to the top. For more related JavaScript animations to return to the top, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!