jQuery: scroll fluido sugli hash

jQuery: scroll fluido sugli hash

Possiamo animare anche i link con hash facendo in modo che lo scroll verso l'elemento sia fluido. In jQuery la soluzione è semplice.

La soluzione è la seguente:


function scrollToElement( speed, hash ) {
	speed = speed || 500;
	hash = hash || null;
	if( hash ) { // L'hash è presente?
		var $target = $( hash );
		if( $target.length ) { // L'elemento esiste?
			$( "html, body" ).animate({
				scrollTop: $target.offset().top
			}, speed);
		}
	}
}

$(function() {
	// Selezioniamo i link che hanno un hash
	$( "a[href^='#']" ).click(function( e ) {
		e.preventDefault(); // Blocchiamo l'azione predefinita
		var linkHash = $( this ).attr( "href" ); // Otteniamo l'hash
		scrollToElement( 400, linkHash );
	});
});

Torna su