webdevlinux - logo Web Dev Linux

How to make a button to scroll to page top

You may have experienced scrolling to page top when you hit Goto top button included in some websites' footer. Adding these kinds of interactivity will improve user experience (UX) and as a result, you will get more traffic.

Smooth scroll to top Scroll to top

There are many smooth-scroll scripts on internet and most of them are based on code libraries like JQuery. Using external code libraries will decrease web page loading speed and it is also a huge disadvantage in UX & SEO (Search Engine Optimization). In this lesson you will understand how to make a very simple & light-weight scroll to top code snippet using HTML, CSS & pure Javascript

General method to jump page top

In the general method to jump page top, We use the hash-mark (#) at the end of page URL or Just the hash-mark as the href attribute of the element <a>. See the code snippet given below

<!-- using hash at the end of link -->
<a href="index.html#">Page Top</a>
<!-- using just the hash -->
<a href="#">Page Top</a>

Scroll to page top

Take a look at the code given below, I have created a very basic web page with some styles for the layout. At the bottom, you will see a script block which is placed just after closing </footer> tag. There are Javascript codes that We use to scroll page to top.

Watch the video at the bottom of page to see how to code step by step the example given in below.

FILE : scroll-to-top.html
<!DOCTYPE html>
<meta charset="utf-8" />
<title>Scroll to page top</title>
header , footer{
	height: 40px;
	width: 100%;
	text-align: center;
	padding:20px 0;
	margin:20px auto;
	font-size: 3em;
	line-height: 5em;
	cursor: pointer;
	color: blue;

	<p>Lorem ipsum dolor sit amet. Vehicula. Nisl cursus nonummy aliquet odio eget, inceptos a. Cubilia suspendisse ante eget, adipiscing quis tellus sodales. Id sociosqu eni, ac aliquet eros, adipiscing. Nostra nisl ve vitae ligula cursus metus.</p>

	<a id="scrollButton">Page Top</a>
	var speed = 10;
	var timer;
	function scrollToTop(k) {
		if (k>0) {
			timer = setTimeout(function () {
		}else clearTimeout(timer);
	document.getElementById("scrollButton").onclick=function () {

In this video you will see how to make a general button to jump page top and then how to modify it to a scroll to top button