JavaScript to implement the back to top button

JavaScript to implement the back to top button

This article shares the specific code for JavaScript to implement the back to top button for your reference. The specific content is as follows

1. Build the scaffolding first

a {
            text-decoration: none;
    }
        
        body {
            height: 5000px;
        }
        
        .backtotop {
            position: fixed;
            bottom: 80px;
            right: 80px;
            width: 80px;
            height: 80px;
            background-color: #ccc;
            font-size: 20px;
            text-align: center;
            padding-top: 12px;
            box-sizing: border-box;
            cursor: pointer;
            color: #000;
            /* Hide the button first */
            /*display: none;*/
        }
<a href="javascript:;" class="backtotop" id="backtotop">Back to<br>Top</a> 

2. Logical part

When the mouse clicks the "Back to Top" button, it will return to the top at a certain "speed" every 50 milliseconds. After returning to the top, it must be cleared, otherwise the page will automatically return to the top as soon as it is pulled down. Two methods are used here, one is setInterval, and the other is clearInterval. The former is to set the timer, and the latter is to clear the timer.
One thing to note here is that in order to avoid conflicts, you must "set the timer first" before setting the timer.
Finally, in order to increase the user experience, we need to design it so that if the current page is at the top, the "Back to Top" button will be automatically hidden; if the current page is not at the top, the "Back to Top" button will be displayed.

.backtotop {
    /* Hide the button first */
    display: none;
}
(function() {
      // 1. Get the element to be operated let oBackBtn = document.querySelector("#backtotop"); 
      // 2. Monitor the scrolling of the web page window.onscroll = function() {
                // Get the scroll distance let offsetY = getPageScroll().y;
                // console.log(offsetY);
 
                // Determine whether to display the rollback button if (offsetY >= 200) {
                    oBackBtn.style.display = "block";
                } else {
                    oBackBtn.style.display = "none";
                }
            }
 
            let timerId = null;
 
            // 3. Listen for clicks on the rollback button oBackBtn.onclick = function() {
 
                //Set the table to close first to prevent timer conflict clearInterval(timerId);
 
                //Set the timer timerId = setInterval(function() {
                    let begin = getPageScroll().y; //Current position let target = 0; //Target position let step = (target - begin) * 0.3;
                    begin += step;
 
                    //Judge whether to end if (Math.abs(Math.floor(step)) <= 1) {
 
                        //Clear timer clearInterval(timerId);
 
                        // window.scrollTo(x, y);
                        // x indicates the position to which the webpage should be scrolled horizontally // y indicates the position to which the webpage should be scrolled vertically window.scrollTo(0, 0);
                        return;
                    }
 
                    window.scrollTo(0, begin);
 
                }, 50);
            };
 
            function getPageScroll() {
                let x, y;
                if (window.pageXOffset) {
                    x = window.pageXOffset;
                    y = window.pageYOffset;
                } else if (document.compatMode === "BackCompat") {
                    x = document.body.scrollLeft;
                    y = document.body.scrollTop;
                } else {
                    x = document.documentElement.scrollLeft;
                    y = document.documentElement.scrollTop;
                }
                return {
                    x: x,
                    y: y
                }
            }
        })(); 

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JavaScript implementation of the back to top button example
  • JavaScript monitors WeChat browser and comes with back button time
  • Implementing the back to top button based on Javascript
  • How to implement the javascript return to top button
  • Implementation of the return to top button in javascript
  • How to prevent the browser back button using JavaScript
  • JavaScript implements the return to top button in the lower right corner of the blog page
  • JS returns to the previous page example code through pictures and buttons respectively
  • js Click the button to pop up another page, select the value and return to the current page
  • Implementation of returning selected data by clicking a button in a JavaScript pop-up form

<<:  In-depth understanding of MySQL slow query log

>>:  Two ways to use IIS to call X-Forwarded-For Header (XFF) to record the visitor's real IP

Recommend

JavaScript singleton mode to implement custom pop-up box

This article shares the specific code of JavaScri...

Detailed explanation of MySQL master-slave replication process

1. What is master-slave replication? The DDL and ...

Solution to MySql service disappearance for unknown reasons

Solution to MySql service disappearance for unkno...

Summary of methods for querying MySQL user permissions

Introduce two methods to view MySQL user permissi...

Detailed introduction to linux host name configuration

Table of contents 1. Configure Linux hostname Con...

HTML table tag tutorial (33): cell vertical alignment attribute VALIGN

In the vertical direction, you can set the cell a...

Application of Hadoop counters and data cleaning

Data cleaning (ETL) Before running the core busin...

Docker link realizes container interconnection

Table of contents 1.1. Network access between con...

Implementation of crawler Scrapy image created by dockerfile based on alpine

1. Download the alpine image [root@DockerBrian ~]...

Detailed explanation of how to use several timers in CocosCreator

1. setTimeOut Print abc after 3 seconds. Execute ...

JavaScript to achieve the effect of clicking on the self-made menu

This article shares the specific code of JavaScri...

React hooks introductory tutorial

State Hooks Examples: import { useState } from &#...