DEV Community

Cover image for 🔝Smooth Scroll-To-Top Functionality Using JavaScript [Easy Way].
Chetan Atrawalkar
Chetan Atrawalkar

Posted on

34 8

🔝Smooth Scroll-To-Top Functionality Using JavaScript [Easy Way].

Halo Guys 👋

In this tutorial we will show you how to add scroll the page to the top smoothly using pure javascript.

Scroll to top buttons allow users to quickly return to the top of a webpage with a single click. This can be very useful when the page has a lot of content.

Image start

  • Let’s start by creating a scrollToTop() function that will contain all the required JavaScript:


function scrollToTop(){
// all JavaScript will go here
};


Enter fullscreen mode Exit fullscreen mode
  • Next inside the scrollToTop() function pass the window.scrollTo() method with two parameters coordinate and behaviour:


function scrollToTop() {
window.scrollTo({
    top: 0,
    behavior: 'smooth'
})
}


Enter fullscreen mode Exit fullscreen mode
  • Next best part is smooth scrolling could be done easily using behavior:'smooth'.

Thats all, this is how to smoothly scroll page to top using javascript. You can customize this code further as per your requirement.

Keep Claim And Just Code It 😎

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (3)

The discussion has been locked. New comments can't be added.
??
Collapse
 
northernbear profile image
Eric

Great Tutorial.
I think you should add your HTML as well and explain how to add and link the button to the JavaScript.
:)

Collapse
 
chetan_atrawalkar profile image
Chetan Atrawalkar

Yup in next part Stay Tuned.....
Thank you ☺️

Collapse
 
deathshadow60 profile image
deathshadow60 • Edited
Comment hidden by post author

Some comments have been hidden by the post's author - find out more

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay