Skip to main content

Scroll to Top of the Page Using JavaScript

Published: Asked By 3 Answers Answered

Scroll to top of the page using Javascript

Share:

3 Answers

A
Amarjith AG Community Contributor Answered on

You can use the window.scrollTo() method in JavaScript to scroll to the top of the page. Here's an example:

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


This code will smoothly scroll the page to the top-left corner. Adjust the behavior parameter to 'auto' for an instant scroll or 'smooth' for a smooth animated scroll.

S
Sooraj Community Contributor Answered on

To scroll to the top of the page using JavaScript, you can use the window.scrollTo() method or window.scroll() method. Here's an example:

javascript
// Using window.scrollTo()
window.scrollTo({ top: 0, behavior: 'smooth' }); // Scrolls smoothly to the top of the page

// Using window.scroll()
window.scroll({ top: 0, behavior: 'smooth' }); // Scrolls smoothly to the top of the page


Both methods will smoothly scroll the page to the top. Adjust the behavior parameter to 'smooth' for smooth scrolling or 'auto' for instant scrolling without animation.

L
LAZIO LEO Community Contributor Answered on

 

You can create a "scroll to top" functionality using JavaScript by setting the scrollTop property of the document.documentElement or document.body elements to 0.
 

<button onclick="scrollToTop()">Scroll to Top</button>

<script>
    function scrollToTop() {
        // For modern browsers
        document.documentElement.scrollTop = 0;

        // For older browsers
        document.body.scrollTop = 0;
    }
</script>

 

Your Answer

Other Resources

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

Q&A Image
Q&A

Ask your coding-related doubts and get answers.

Certification Image
Certification

Earn certifications to enhance your resume.

internships Image
Internships

Hands-on projects to improve your skills.

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

blog Image
Blogs

Add your technical blogs and read technical topics.

Certification Image
Certifications

Earn certifications to enhance your resume.