JavaScript Scroll to the Top of Page

In this tutorial we will learn how to Scroll to the Top of Page on click with JavaScript. We can use scrollTo() method and onclick event for this which will scroll the page to the top on click of a button.

scrollTo() method

scrollTo() method scrolls the page to defined coordinates.

In this simple example we have also used scrollTo() method to scroll the page to the top.

onclick event

onclick event triggers the click event for HTML tag or it attaches the function execution with a click event.

In this example onclick event will execute a function which will scroll the page to top.


HTML Code is given below, in this code we have a button tag with onclick event.

<!DOCTYPE html>
<title>JavaScript Scroll to the Top of Page</title>
<body style="height: 10000px;">

<button onclick='scrollToTop()' style="position: fixed;">Scroll To Top</button>    
<script src="script.js"></script>    

JavaScript Code

Take a look at the JavaScript code, In this code scrollTo() method has both zero x and y coordinates.

This value is in pixels so the page will move to the top position.

function scrollToTop()


Video Tutorial

Watch video tutorial on How To Scroll Page to the Top on Click with JavaScript.

How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color JavaScript Change li Text JavaScript Remove id from Element Check If id Exists in JavaScript How To Delete Table Row by id in JavaScript Update Textarea value in JavaScript Change Variable Value in JavaScript Uncheck Radio Button Dynamically JavaScript Check Radio Button Dynamically JavaScript JavaScript Check if Radio Button is Checked or Not Change h1 Tag Text with JavaScript