Smooth scroll animation without the use of jQuery

I am experimenting with creating an animated "scroll to top" functionality without relying on jQuery.

Typically, in jQuery, I would implement this code:

$('#go-to-top').click(function(){ 
      $('html,body').animate({ scrollTop: 0 }, 400);
      return false; 
});

Is there a way to achieve the same scroll animation effect without using jQuery?

Answer №1

Code Example in HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript Function (linear scrolling):

function scrollToTopLinear(duration) {
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step(newTimestamp) {
        if (oldTimestamp !== null) {
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript Function (ease in and out scrolling):

function scrollToTopEase(duration) {
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step(newTimestamp) {
        if (oldTimestamp !== null) {
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    For more information see the link provided above.
*/

Note:

  • Duration is in milliseconds (1000ms = 1s)
  • The second script utilizes the cosine function for smooth scrolling.

3# Explore a scrolling library on Github

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

What is the best way to send a form value to a servlet?

As someone who is relatively new to programming, I kindly ask for your patience with me. I am currently attempting to extract values from a form (embedded in a JSP) using JavaScript, and then make a post request to a servlet. The form consists of 6 differ ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...

Is it actually feasible to automate and interact with web elements in a NW.js exe app? I have created a JavaScript script to open and test it

A test case for nw.js can be found in the official NW.js documentation. The original test case is written in Python, but I attempted to recreate it in JavaScript. However, I encountered an error that made it difficult to interact with elements in the nw.ex ...

Using Express.js, Passport.js, and SockJS to Link User Socket with deserializeUser

Recently, I have been working on a new project where I am utilizing Express 3, Passport.js, and SockJS. One of my requirements is to attach the user socket to the User instance so that I can use it in route handlers, such as for notifications. The code sni ...

Is it possible to pass a parameter to a PHP controller using JavaScript without relying on jQuery or AJAX?

Is it possible to achieve the task at hand? That's the main question here. My goal is to extract data from a popup window and then, upon closing it, send this extracted content to a PHP controller for further processing. I'm facing conflicts wi ...

Problem encountered while storing data in mongoose database

Within my users route. const User = require('../models/user'); router.route('/verify') .get( (req, res) => { res.render('verify'); }) .post( (req, res, next) => { const {secretToken} = req.body; ...

execute a function from a separate file in a node.js environment

How can I call the /getJobs endpoint inside the job.js node script? I'm currently using this approach, but I'm receiving an error stating "$ is not defined". job.js var jobSchedule = function (time, jobId) { var params = { "id": jo ...

Callback for Variable Change

Is there a way to have a function trigger when a variable changes its value? In the code snippet provided, there is a function called loadImage that fetches the image material. However, if this code is executed, the declaration of mesh and scene.add(mesh) ...

Update the text within a textarea using jQuery

I am interested in creating a personalized text stylizer tool that allows users to select a portion of text in a textarea and apply custom "post-stylizer" buttons. Similar to the functionality seen here on Stackoverflow. I have searched the forums but have ...

Tips for obtaining the total height of an SVG illustration

As a novice, I am currently attempting to convert a PSD file into HTML. My main goal is to achieve the full height of the background image within the .hero class. What steps should I take to accomplish this successfully? * { margin:2px; } .container{ ma ...

center text above images in flexbox when page is resized

When resizing the page, I'm facing an issue where the links overlap with the images in a flexbox layout. It seems like the padding and margin between the images and links are not working due to them not being "related" or connected. I believe I need t ...

Is it possible to use a figure tag as a fancybox link?

I am curious, is it possible to turn a figure tag into a fancybox link with just a background image and no content? I understand that this may not be recommended, but I am wondering if it can actually be achieved? <figure class="appear"><a class= ...

Next.js 13 React Server Component not displaying updated data upon build completion

I have a React Server Component that retrieves its data at build time and does not reload it while the site is running. I expected it to fetch the data once when the server component is first rendered. Is there a way to force this server component to relo ...

What is the best way to apply fading effects to three divs containing additional divs?

Looking at this HTML and CSS code: HTML <DIV class="newsPic"></DIV> <DIV class="newsPicTwo"></DIV> <DIV class="newsPicThree"></DIV> CSS .newsPic { width: 500px; height: 200px; } .newsPicTwo { width: 500px; height: 2 ...

The button's color cannot be modified due to a malfunctioning event script that is not

Seeking an explanation for why my current implementation isn't working. I'm attempting to create a quiz with a multiple choice section where the correct answer turns green when clicked, and incorrect answers turn red. Despite validating the code ...

JavaScript Error Caused by Newline Characters

I'm facing an issue with extracting data from a textbox using JavaScript. What I'm attempting to do is retrieve the value from a textbox, display it in an alert, and then copy it. Here's the current code snippet: var copyString = "Date: < ...

Scrolling in Bootstrap 4 Cards conceals the fixed Header

Here's some HTML code featuring Bootstrap 4 elements. It showcases a fixed Header and Footer with scrollable Bootstrap Cards in between. When scrolling, the Headers may be hidden by the Cards. How can you adjust the layout so that the Cards scroll "be ...

Set the local storage value to the $scope variable

I am attempting to set a local storage value to a $scope variable and utilize that $scope variable in ng-model to populate dropdowns. However, the code I have tried is not functioning as expected. You can view the Plunker example here: https://plnkr.co/ed ...

How to merge multiple hover effects using JS or JQuery

I am just beginning my journey as a web designer and currently delving into the world of JavaScript for enhancing website functionality. While working on my latest project, I encountered a challenge. I wanted to create a menu where specific elements would ...

The issue of blank spaces appearing in Outlook 2007 within conditional comments

Having been immersed in the world of coding HTML emails for several years, I've encountered numerous conditional comment-based 'bulletproof buttons' available online. While most of them do the job just fine, I've hit a roadblock with Ou ...