Use Javascript and jQuery to Scroll To Area of Webpage

11/22/2013 8:47:31 PM

The following will show an image allowing the user to scroll to the top of a webpage whenever they start scrolling down. A user will click the icon, the page will smoothly scroll up and the scroll up icon will fade out. When the user scrolls ldown again, the scroll up icon will re-appear.

This code requires jQuery.

<div class="scrollToTop" id="divScrollToTop">
	<img id="imgScrollToTop" src="/siteresources/images/scroll-to-top.png" />
</div>
	
<script type="text/javascript">
	$(document).ready(function ()
	{
		// fade in #back-top
		$(function ()
		{
			$(window).scroll(function ()
			{
				if ($(this).scrollTop() > 100)
				{
					$('#imgScrollToTop').fadeIn();
				}
				else
				{
					$('#imgScrollToTop').fadeOut();
				}
			});

			// scroll body to 0px on click
			$('#imgScrollToTop').click(function ()
			{
				$('body,html').animate({
					scrollTop: 0
				}, 400);
				return false;
			});
		});
	});

</script>