Back jQuery

Disappearing Scroll to top link with jQuery and CSS

WRITTEN BY ON 09 Jan 2011
19,346 VIEWS • SHARES
2 comments

The disappearing back-to-top link was inspired by Brian Cray. Scroll to top links are very useful, but you never know when a user needs to jump back up. Here's a simple to implement "scroll to top" link that only displays after the user begins scrolling.

HTML/XHTML

<body>
<div id="top"></div>
<!-- put all of your normal <body> stuff here -->
<div id="message"><a href="top">Scroll to top</a></div>
</body>

CSS

#message a
{
	/* display: block before hiding */
	display: block;
	display: none;
 
	/* link is above all other elements */
	z-index: 999; 
 
	/* link doesn't hide text behind it */
	opacity: .8;
 
	/* link stays at same place on page */
	position: fixed;
 
	/* link goes at the bottom of the page */
	top: 100%;
	margin-top: -80px; /* = height + preferred bottom margin */
 
	/* link is centered */
	left: 50%;
	margin-left: -160px; /* = half of width */
 
	/* round the corners (to your preference) */
	-moz-border-radius: 24px;
	-webkit-border-radius: 24px;
 
	/* make it big and easy to see (size, style to preferences) */
	width: 300px;
	line-height: 48px;
	height: 48px;
	padding: 10px;
	background-color: #000;
	font-size: 24px;
	text-align: center;
	color: #fff;
}

JS - jQuery

$(function () { // run this code on page load (AKA DOM load)
 
	/* set variables locally for increased performance */
	var scroll_timer;
	var displayed = false;
	var $message = $('#message a');
	var $window = $(window);
	var top = $(document.body).children(0).position().top;
 
	/* react to scroll event on window */
	$window.scroll(function () {
		window.clearTimeout(scroll_timer);
		scroll_timer = window.setTimeout(function () { // use a timer for performance
			if($window.scrollTop() <= top) // hide if at the top of the page
			{
				displayed = false;
				$message.fadeOut(500);
			}
			else if(displayed == false) // show if scrolling down
			{
				displayed = true;
				$message.stop(true, true).show().click(function () { $message.fadeOut(500); });
			}
		}, 100);
	});
});
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

2 comments
Clecio Espindola 12 years ago
Man, it works greatly for me... Thanks a lot
Reply
Philipp Walzer 12 years ago
Any idea why it's not working here? The link shows up but when I click it it I get a NOT FOUND error...

http://stage.what-army.com/crystalsprings/index.html
Reply