jQuery: implementare un link "Torna su" ( Back to top )

jQuery: implementare un link "Torna su" ( Back to top )

Un link "Torna su" (o "Back to top") è estremamente semplice da implementare con jQuery.

Quello che dobbiamo fare è animare la proprietà scrollTop reimpostando il suo valore a 0:


$( "#back-to-top" ).on( "click", function( e ) {
	e.preventDefault();
	$( "html, body" ).animate({
		scrollTop: 0
	}, 500 });
});

La tecnica di base può essere migliorata creando un plugin:


(function( $ ) {
	
	$.fn.backToTop = function( options ) {
		options = $.extend({
			speed: 500,
			easing: "linear",
			callback: function() {}
		}, options);
		
		return this.each(function() {
			var $element = $( this );
			
			$element.on( "click", function( e ) {
				e.preventDefault();
				$( "html, body" ).animate({
					scrollTop: 0
					
				}, options.speed, options.easing, options.callback );
				
			});
			
		});	
	};
	
})( jQuery );

Esempio d'uso:


$( "#back-to-top" ).backToTop({
	speed: 400,
	callback: function() {
		// Azione da eseguire ad animazione completata	
	}
	
});

Torna su