Add Scroll to top button in your webpage

If you want to add Scroll to top button then you can simply use window.scrollTo() methid of JavaScript. But it will not provide smooth scrolling. For smooth scrooling you need to use below snippet of JavaScript & CSS.

<!DOCTYPE html>
<html>
<head>
	<title>Scroll to Top</title>
	<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
	<style type="text/css">
		#top{opacity:0.8;position:fixed;bottom:15px;right:15px;display:none;}
		#top img{height: 20px;cursor: pointer;}
	</style>
</head>
<body>
	<h3>Scroll to Top Demo</h3>
	<!--
	Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>Long Long Content.<br>
	-->

	<div id="top"><img src="http://findicons.com/files/icons/2232/wireframe_mono/48/arrow_top.png"></div>


	<script type="text/javascript">
		$(document).ready(function(){

			// Hide/show Scroll to Top Image
			$(window).scroll(function(){
				if ($(this).scrollTop() > 100) {
					$('#top').fadeIn();
				} else {
					$('#top').fadeOut();
				}
			});

			// Add Scrolling Effect
			$('#top').click(function(){
				$("html, body").animate({ scrollTop: 0 }, 600);
				return false;
			});

		});
	</script>
</body>
</html>

Note that this code using jQuery methods, so you need to use jQuery.min.js file into your page. Click here to download above snippet as HTML file.

Leave a Reply

Your email address will not be published. Required fields are marked *