How can you implement window.scrollTo animation in JavaScript without using jQuery?

Despite my efforts to find a solution written in JavaScript, I keep getting answers related to jQuery. So, how can I implement animation using window.scrollTo in pure JavaScript? I tried using setInterval but it didn't work. Any assistance on this matter would be greatly appreciated.

Answer №1

After hours of searching, I finally discovered the solution to smoothly scroll by passing this object:

window.scrollTo({
  top: selectedFrame.offsetTop,
  left: 0,
  behavior: 'smooth'
});

Please note that the smooth option may not be supported in Safari.

For more information, refer to: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo

Answer №2

Give this a try.

window.scrollTo(0, 0);

I personally recommend using this method to smoothly scroll from the bottom to the top of the page using JavaScript.

Alternatively:

HTML

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

Javascript

 function scrollToTop(scrollDuration) {
  var scrollStep = -window.scrollY / (scrollDuration / 15),
    scrollInterval = setInterval(function(){
    if ( window.scrollY != 0 ) {
        window.scrollBy( 0, scrollStep );
    }
    else clearInterval(scrollInterval); 
 },15);
}

Answer №3

Here's the solution that did the trick for me:

function scrollToElement(id) {
    var targetElement = document.getElementById(id);
    document.body.scrollTo({
        top: targetElement.offsetTop,
        behavior: 'smooth'
    });
}

Answer №4

I implemented a sophisticated scrolling function inspired by the insights shared by @SachinShah above to cater to my specific requirements.

This could be beneficial for someone else facing similar needs.

Before delving into its functionality, let me outline what it accomplishes:

  • It smoothly scrolls to a designated element's id
  • Follows a specified duration seamlessly
  • Offers an option to adjust the target offset, particularly useful when dealing with sticky/smart headers
  • Allows control over the smoothness of the scroll using setInterval function

Please bear in mind that:

  • The method utilizes the relative scrolling approach window.scrollBy, necessitating the determination of scrollDirection (up/down) within the logic
  • Both scrollDuration and scrollSmoothness are measured in milliseconds
/**
 * Scroll to the top of the page in a specified duration(ms) and smoothness(ms)
 * ref: https://stackoverflow.com/a/52478645/3556531
 * @param {String} elementID
 * @param {Int} scrollDuration
 * @param {Int} offset
 * @param {Int} scrollSmoothness
 */

const fancyAScroll = (
  elementID = 'main-content',
  scrollDuration = 500,
  offset = 0, // I  had to use 120 to compensate for a sticky header
  scrollSmoothness = 10
) => {
  const accuracyBuffer = 10
  try {

    // #1 Calculate the final offset position to scroll-to
    const element = document?.getElementById(elementID)
    const bodyRect = document?.body?.getBoundingClientRect().top
    const elementRect = element?.getBoundingClientRect().top
    const elementPosition = elementRect - bodyRect
    const offsetPosition = elementPosition - offset // final - target position to scroll

    // #2 calculate steps & direction (up or down)
    const scrollStepUnit = offsetPosition / (scrollDuration / scrollSmoothness)
    const scrollStepDirection = offsetPosition > window?.scrollY ? '' : '-'
    const scrollStepY = `${scrollStepDirection}${scrollStepUnit}`

    // #3 keep on relatively scrolling untill reached to the destination
    const scrollInterval = setInterval(() => {
      let targetRangeReached =
        offsetPosition - accuracyBuffer < window.scrollY &&
        window.scrollY < offsetPosition + accuracyBuffer

      targetRangeReached ? clearInterval(scrollInterval) : window.scrollBy(0, scrollStepY)
    }, scrollSmoothness)
  }
  catch (error) {
    console.error('Error @scrollTopWithDuration\n', error)
  }
}

export default fancyAScroll

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

Setting up language preferences without having to reload the entire page

Is there an alternative method to change the app language without refreshing the entire page? The code snippet below always refreshes the page, leading to a poor user experience. window.location.search = "sap-language=EN"; The following code snippet is a ...

Using Typescript to create a Checkbox Grid that displays pipe-delimited values and implements a custom validation rule

I am currently working with a checkbox grid that contains pairs of AccountIds (consisting of x number of digits) and file names separated by a pipe delimiter. The file names are structured to always begin with either PRC or FE followed by a varying combin ...

Using multiple words as input for an Alexa Skill

My current project involves creating an Alexa skill that is capable of receiving multiple words as input and reading them out to the user. To achieve this, I have defined the following Intent Schema: { "intents": [ { "intent": "AMAZON.Cancel ...

The use of refs on Function components in SVG is not supported. Any attempts to access the ref will result in an

I am currently working on integrating a navigation bar component using an SVG image in Next.js. While attempting to import and utilize the SVG image, I encountered an error that I couldn't resolve. I tried using Emotion JS to create and use the SVG, ...

There seems to be an issue with React-hook-form and material-ui not retaining value changes in the onBlur() method

Stepping into the realm of react-hook-form is a new experience for me. I'm putting in effort to grasp everything, but there are still some pieces missing from the puzzle. Seeking assistance akin to Obiwan Kenobi! The Dilemma at Hand: An <Textfiel ...

Unable to locate the Shadcn error module: Error encountered when trying to resolve the path '@/components/ui/accordion' within the directory 'Desktop/sadcn/src'

I'm encountering an issue with my Shadcn setup in a simple React app with TypeScript. The error message I'm getting is: Module not found: Error: Can't resolve '@/components/ui/accordion' in '/home/vinayak/Desktop/sadcn/src&ap ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

Modifying the content of a paragraph by incorporating information from various sources

I need a way to input measurements for my items in text fields, and then with the click of a button, transfer those measurements into a paragraph in corresponding fields. The code I am currently using is shown below: <!DOCTYPE html> <html> & ...

Experiencing difficulties connecting with aspx while using Ext JS 4.2

Currently, I am facing an issue with making a call to an ASPX URL as the return keeps coming back as a failure. I have successfully used this URL in previous programming projects, but this is my first time utilizing it with Ext JS. Despite researching dif ...

Dynamic JavaScript Line Graph

I am facing a challenge with a small function in my application that needs to display real-time data on a webpage. I have been exploring different Javascript examples, such as the Flot example "real-time updates" and the Highcharts example "spline updating ...

The dynamic URL parameters are altered by the Browser's back button

I am currently working on a website where the URL parameter is updated based on user actions. This update triggers changes in the webpage without the need for refreshing. An example scenario would be in an E-commerce site where the URL changes when the use ...

There appears to be some lingering content in the JQuery Mobile slide-out dialog box

My jQuery mobile slide out dialog box is experiencing an issue. The first time the slide out occurs, a comment box appears where users can enter comments and then submit them, followed by a "THANK YOU" message. However, when the user closes the dialog box ...

JavaScript XML Serialization: Transforming Data into Strings

When trying to consume XML in an Express server using express-xml-bodyparser, the resulting object is not very useful. This is the XML: <SubClass code="A07.0"/> <SubClass code="A07.1"/> <SubClass code="A07.2"/> <SubClass code="A07.3" ...

Back to top button displayed exclusively on desktop view (not visible on mobile devices)

I managed to create a scroll-to-top button that only appears when the user has scrolled down 25px from the top of the document. I achieved this using JavaScript by following a tutorial, as I am still unfamiliar with this programming language. However, I w ...

Looking to incorporate multiple accordion drop down menus on your website? Utilize a combination of HTML, CSS, and JavaScript to

I am experiencing a challenge with implementing multiple accordion menus on my website. Whenever I attempt to duplicate the code, the new accordion menu appears but clicking on the first bar simply scrolls me back to the top of the webpage. Below is the H ...

Exploring the relationship between MongoDB and Node.js: Retrieving a document based on its _id using a UUID (GUID

As I work on creating a restAPI with node.js, I am facing an issue while querying a mongo collection. While I can successfully query using strings such as "companyname", I struggle when it comes to querying the "_id" element in the document. In my mongo d ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Express API encounters an issue with multer and body-parser as req.file is undefined

I am in the process of developing an API that will need to handle file uploads along with other GET and POST requests. To manage file uploads, I am using 'multer' while utilizing 'body-parser' for all other HTTP requests. My goal is to ...

When array.push is used inside another array, it results in an undefined value

While working on defining an array within the Fire array in my code, I encountered a problem. When I tried to use console.log() to display the length of the array inside the Fire[] array for debugging, I received an error indicating that the array was und ...

Questioning the way spyOn "halts all execution of a function" is described in the Jasmine documentation (specifically in the section on Spies in version 2.2)

I am struggling to comprehend the last test in the Jasmine 2.2 documentation which showcases the basic usage of Spies. In the beforeEach() section, we initialize bar = null, then we spy on foo.setBar and proceed to call foo.setBar twice. I am puzzled as t ...