jQuery: animare lo scroll sugli hash

Possiamo animare anche gli hash con jQuery facendo in modo che lo scroll verso l'elemento sia fluido.

jQuery di Gabriele Romanato

Possiamo animare anche gli 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 );
	});

    // Usiamo location.hash

    scrollToElement( 400, location.hash );
});

Commenti