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

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

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

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

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.

<script>
function scrollToTop()
{
    window.scrollTo(0,0);
}
</script>

Demo

Video Tutorial

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

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using 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