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

36 principles of MySQL database development (summary)

Preface These principles are summarized from actu...

How to install Docker on Windows 10 Home Edition

I recently used Docker to upgrade a project. I ha...

HTML uses form tags to implement the registration page example code

Case Description: - Use tables to achieve page ef...

JavaScript Html to implement the mobile red envelope rain function page

This article example shares the specific code of ...

Summary of the use of html meta tags (recommended)

Meta tag function The META tag is a key tag in th...

How to install php7 + nginx environment under centos6.6

This article describes how to install php7 + ngin...

About the layout method of content overflow in table

What is content overflow? In fact, when there is ...

Implementation of HTML sliding floating ball menu effect

CSS Styles html,body{ width: 100%; height: 100%; ...

Detailed explanation on reasonable settings of MySQL sql_mode

Reasonable setting of MySQL sql_mode sql_mode is ...

MySQL controls the number of attempts to enter incorrect passwords

1. How to monitor MySQL deadlocks in production e...

JavaScript to achieve simple drag effect

This article shares the specific code of JavaScri...

Steps to install MySQL using Docker under Linux

As a tester, you may often need to install some s...

How to change the encoding of MySQL database to utf8mb4

The utf8mb4 encoding is a superset of the utf8 en...