Creating a button that allows users to quickly navigate back to the top of a webpage

On my website, I have a convenient "back to top" feature that allows users to easily navigate back to the top of the page:

If you scroll down the page, you'll see this feature in action. This particular feature is part of the theme I'm using on Wordpress.

For learning purposes, I want to replicate this feature on another page of a different site. So far, I've managed to gather all the necessary components up to this point:

The issues I'm encountering are:

  • The size of the box is not consistent
  • The alignment of the chevron is off
  • No action occurs when clicking the chevron
  • The box remains visible at all times

What steps am I missing here?

Update

Following some suggestions, I have added a couple of script lines. Here's what's currently present in the head section:

<!-- code snippets -->

Although there has been some improvement, the issue now is that the scrolling is abrupt and not smooth. I'm puzzled as to why the JavaScript function is not being executed properly.

Answer №1

Check out this helpful guide on creating a scroll back to top button: How TO - Scroll Back To Top Button

// Display the button when the user scrolls down 20px from the top of the page
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        document.getElementById("myBtn").style.display = "block";
    } else {
        document.getElementById("myBtn").style.display = "none";
    }
}
  
$('#myBtn').on('click', function (e) {
    e.preventDefault();
    $('html,body').animate({
        scrollTop: 0
    }, 700);
});
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}

#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}

#myBtn:hover {
background-color: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="myBtn" title="Go to top">Top</button>

<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>

Answer №2

If you want to calculate how far you need to scroll and then implement smooth scrolling using animation frames, JavaScript can come in handy.

Check out this project for a simplified approach that I've modified.

The section at the end with querySelectorAll specifically targets internal anchor links and converts them into scroll buttons.

function smoothScroll(destination, duration = 350) {
  const startingPoint = window.pageYOffset;
  const startTime = 'now' in window.performance ? performance.now() : new Date().getTime();
  const body = document.body;
  const html = document.documentElement;

  const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
  const winHeight = window.innerHeight || html.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
  const destOffset = typeof destination === 'number' ? destination : destination.offsetTop;
  const destScrollOffset = Math.round(docHeight - destOffset < winHeight ? docHeight - winHeight : destOffset);

  if ('requestAnimationFrame' in window === false) {
    window.scroll(0, destScrollOffset);
    return;
  }

  function scrollAnimation() {
    const currentTime = 'now' in window.performance ? performance.now() : new Date().getTime();
    let timeElapsed = Math.min(1, ((currentTime - startTime) / duration));
    let timeFunction = timeElapsed;
    window.scroll(0, Math.ceil((timeFunction * (destScrollOffset - startingPoint)) + startingPoint));

    window.pageYOffset === destScrollOffset || requestAnimationFrame(scrollAnimation);
  }

  scrollAnimation();
}

document.querySelectorAll('a').forEach(el => {
  el.addEventListener('click', (e) => {
    const link = e.target.getAttribute('href');
    if (link.match(/^#/)) {
      e.preventDefault();
      if (link.match(/^#$/)) {
        smoothScroll(0);
      } else {
        smoothScroll(document.querySelector(link));
      }
    }
  })
})
<div>
  test <a href="#test">to bottom</a>
</div>

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>

<div id="test">
  test <a href="#">to top</a>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

I trust you will find this information beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Methods for inserting text into a WebBrowser Document without retrieving any Attributes in vb.net

Is it possible to retrieve text from a WebBrowser Document in vb.net without retrieving any attributes?! For example: <h1>text here</h1> Or: <h1 name="anything">text here</h1> How can I extract the "text here" within the <h1 ...

Errors are being displayed in the console when attempting to use Vuex getters in a component. This is happening because the Vuex state properties are still null at the time the getters

When assigning results from GET requests to my Vuex state properties, it's expected that they won't be available instantly. However, I have a getter like the following: findChampion: (state) => (id) => { let championId = id.toString() ...

Utilizing React for Conditional Rendering and Navigation Bar Implementation

When developing my applications in react-native, I am using the state and a switch statement in the main render function to determine which component should be displayed on the screen. While this is a react structure question, it has implications for my sp ...

Extract the value from JSON data

I am faced with the challenge of extracting the value of slug from each child in a JSON dataset. The issue lies in the fact that I cannot predict how many children will be generated whenever new data is received. The generation of nested children is dynam ...

Are the buttons appearing within a pop-up display?

I am having an issue with my Javascript popup buttons. Whenever the popup appears, the buttons that come after the one clicked appear on top of the popup container, and the previous buttons appear behind it. How can I ensure that the popup container displa ...

In the world of three js, we are presented with two distinct scenes featuring CubeGeometry and PointsGeometry. However

I've been trying to generate a cube and some dots that are part of a torus using the code below. However, I can only see the cube and not the dots. Despite spending hours searching for the dots, they remain elusive. // Generating a cube cu ...

I can't figure out why this error keeps popping up in React JS: "You are attempting to use withTheme(Component) with a component that is undefined."

https://i.sstatic.net/CSxtJ.png Ever since I installed some "material-ui" packages, I've been encountering this annoying error. I've attempted various solutions but to no avail. Can anyone lend a hand? ...

Anticipated that the absence of a value would match the presence of an Object

Struggling with running AngularJS unit tests for $resource using Jasmine v2.0 and Karma v0.13, I managed to convert custom actions to newer syntax successfully. However, a specific type of test is giving me trouble, which I suspect is related to $httpBacke ...

Is there a way to refresh a different webpage within the current session?

In the world of Asp.Net 4, there is a form waiting to be filled with numeric data by the customer. However, this task can sometimes prove tricky as customers may struggle to calculate and input the total figure for each of the four fields. An innovative s ...

I am struggling with grasping the concept of the event system

I'm encountering an issue with the following code snippet: <template> <div class="chart" v-bind:style="chartStyleObject" v-on:mousedown.left="initHandleMousedown($event)" v-on:mouseup.left="initHandleMouseu ...

Stop users from highlighting text on a webpage

There is a div element on my HTML page that always displays the "can't drop" cursor whenever I click and move the mouse, as if it is trying to select something. I have attempted to disable this selection behavior using the CSS property user-select wit ...

Is there a way to move the <hr> element closer to the content in the header section?

I am looking to move the closer to the content in the header. I attempted using position-absolute but the disappeared. This marks my inaugural project with bootstrap. <!-- Bootstrap-5 --> <link href="https://cdn.jsdelivr.net/npm/<a href="/ ...

Using a string as a key for an object's property

function createObject(argName, argProperties){ var object = {}; object[argName] = argProperties; } I am calling my function in the following manner. createObject('name', objectProperties); The issue I am encountering is w ...

What is the best way to include scrollbars with bootstrap?

I recently came across this HTML code snippet from a learning website: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Example of Bootstrap 3 Simple Tables</title> <link rel="stylesheet" href="htt ...

Does Google's caching process differ when using <span> tags instead of <h> tags for headings?

Does the choice between using <span class="heading"> and <h> tags impact search engine optimization for Google? As I'm constructing a website, I decided to style the headings and subheadings with <span>. However, I began to wonder i ...

The CSS keyframe for mobile devices initiates from 100% and then proceeds to animate

Having some trouble with CSS animations on mobile devices. The animation works perfectly fine on desktop, but on mobile, it seems to display the final 100% keyframe first before animating from 0%. I've tried adding the initial style directly to the cl ...

Using CSS to add color to the border of a shape

Is there a way to make only the top, shaped part of this polygon have a 2px blue outline? .graph { clip-path:polygon(0 78%, 9% 67%, 32% 77%, 56% 60%, 69% 30%, 88% 40%, 100% 20%, 100% 100%,0 100%); border:none; height:200px; width:100%; ...

How to utilize JS variables for filtering an array in EJS?

Is there a way to filter my user array based on the "username" variable in JavaScript? On the server side: var users = data.filter(u => u.id.startsWith('user_')).map(u => u.value); // [{"username": "arin2115", "som ...

Using ES6 without the need for jQuery, populate a select element with JSON data using Javascript

I have a json-formatted dataset that I want to incorporate into my select options. Here is the data: { "timezones": { "country": "Africa", "tz": "Africa/Abidjan" }, { "country": "America", "tz": "America/ ...

What is the process of creating and customizing popovers in Bootstrap 5 with jquery?

Is there a way to dynamically create and add content to Bootstrap 5 popovers using JavaScript or jQuery? In Bootstrap 3, I used the following method: $('#element').popover({ placement : 'left', trigger : 'focus', html: true } ...