Dynamic Top Link Revisited

Explications

By adding the following codes to your page you can dynamically show the "to the top" button. A HTML only fallback is available even when the JavaScript is de-activated.

En incluant les codes ci-dessous à votre page, vous incluez le bouton "Haut de page" dans votre page HTML. Cette solution fonctionne mème sans JavaScript.

HTML Code

<div id="top-link" class="top-link"><a href="#top" title="to the top">&uarr;</></div>

CSS Code

To ease the CSS readability I've removed prefixed rules from the code.

.top-link { 
	position:fixed; 
	bottom:7px; 
	right:7px; 
	margin:0; 
	padding:0; 
	z-index:999; 
	transition:all .4s linear;
}

.top-link.top-link-hide { 
	opacity:0;
}

.top-link a { 
	display:block; 
	margin:0; 
	padding:5px; 
	width:14px; 
	opacity:.4; 
	color:#fff; 
	font:bold 15px/1 arial, sans-serif; 
	text-decoration:none; 
	text-align:center;
	text-shadow:0 1px 0 rgba(0, 0, 0, .5);
	border:3px solid #fff; 
	border-radius:50%; 
	box-shadow:0 0 2px rgba(0, 0, 0, .5);
	background-color:#d10e52;
	transition:all .4s linear;
}

.top-link:hover a { 
	opacity:1;  
	transform:scale(1.2);
}

JavaScript Code

This code works with jQuery 1.7+
jQuery(function($){
	var showToTheTopLink = function() {
		var topLink = $('#top-link');
		if (topLink.length != 1) { //if no button was found the script add one in the page
			topLink = $('<div id="top-link" class="top-link"><a href="#top">&uarr;<\/a><\/div>').appendTo($('body'));
		}
		if ($(window).scrollTop() > 0) {
			if(topLink.hasClass('top-link-hide')) {
				topLink.removeClass('top-link-hide');
			}
		} else {
			if(!topLink.hasClass('top-link-hide')) {
				topLink
					.addClass('top-link-hide')
					.find('a')
					.removeClass('top-link-clicked');
			}
		}
	};
	$(window)
		.scroll(function(){ showToTheTopLink(); })
		.on('click', '#top-link a', function(e) {
			e.preventDefault();
			if ($(window).scrollTop() > 0 && !$(this).hasClass('top-link-clicked')) {
				$(this).hasClass('top-link-clicked');
				$('html, body').animate({scrollTop: $('html').offset().top}, 2E3);
			}
		});
	showToTheTopLink();
});