Dynamic Go-to-Top Link In jQuery

Instead of displaying a perpetual “go to top” link for every page, here’s a quick way to dynamically display the link only if the content height is greater than that of the browser window. So it’s there when you need it, not when you don’t. Just include the following snippet of jQuery with your design:

// dynamic top link @ http://perishablepress.com/dynamic-top-link/
function xycss_dynamic_top_link(){
	if($(window).height() < $(document).height()) {
		$('body').append('<div id="top-link">&uarr;</div>');
		$('#top-link').click(function() {
			window.location = "#top";
		}).css({
			width:'24px', height:'24px', lineHeight:'24px', bottom:'3px', right:'3px', 
			background:'#663300', color:'#fff', opacity:0.3, zIndex:999, textAlign:'center', 
			textDecoration:'none', position:'fixed', cursor:'pointer',
			border:'3px solid #c7bc8e', borderRadius:'24px'
		}).hover(function(){
			$(this).css('opacity',0.6);
		},function(){
			$(this).css('opacity',0.3);
		});
	}
}
$(document).ready(function(){
	xycss_dynamic_top_link();
});
$(window).resize(function() {
	$('#top-link').remove();
	xycss_dynamic_top_link();
});

That’s pretty much it, should be plug-n-play. I’ve included the same CSS styles I use here at the site, for the circle with the “up” arrow (see lower-right corner of the page). When the page content exceeds the height of the browser window, the top link is included using the following markup:

<div id="top-link">&uarr;</div>

This markup will serve as a “clickable” link that will take the user to the top of the page. So you can style it directly with #button and/or #top-link. See the various .css() parts of the code to change the link’s appearance and so forth.

And of course if the user doesn’t have JavaScript, they’ll can just use their browser’s default scrollbars, swipes, or whatever.

Advertisements
By Rz Rasel Posted in jQuery

3 comments on “Dynamic Go-to-Top Link In jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s