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.
Table of Contents
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.