Scrolling a parallasse in puro JavaScript

Scrolling a parallasse in puro JavaScript

Le transizioni CSS combinate con JavaScript ci permettono di ottenere una vasta gamma di effetti, incluso quello dello scrolling a parallasse.

Per prima cosa definiamo la proprietà transition sul contenitore generale:


#site {
	width: 100%;
	position: relative;
	transition: all 800ms ease-in;
	top: 0;
}

Abbiamo quindi una serie di link di navigazione:


<nav id="navigation">
	<a href="#home">Home</a>
	<a href="#section-1">Section 1</a>
	<a href="#section-2">Section 2</a>
</nav>

Ogni hash contiene il riferimento alla sezione corrispondente ( ad esempio #section-1). Grazie a questi hash possiamo selezionare la sezione corrente, ottenere il suo offset verticale e modificare la proprietà top del contenitore generale in base al valore ottenuto.


(function() {
	function Parallax( element ) {
		this.element = document.querySelector( element );

		this.init();
		this.navigate();
	}

	Parallax.prototype = {
		init: function() {
			this.navItems = document.querySelectorAll( "#navigation a" );
		},
		navigate: function() {
			var self = this;
			var items = self.navItems;

			for( var i = 0; i < items.length; ++i ) {
				var item = items[i];
				item.addEventListener( "click", function( e ) {
					e.preventDefault();
					var targetExpr = this.getAttribute( "href" );
					var target = document.querySelector( targetExpr );
					self._gotoSection( target );
				}, false);
			}

		},
		_gotoSection: function( element ) {
			var top = element.offsetTop,
				y = 0;
			if( top !== 0 ) {
				y = top - element.scrollTop - 80;
				this.element.style.top = "-" + y + "px";
			} else {
				this.element.style.top = y + "px";
			}
			
		}
	};

	document.addEventListener( "DOMContentLoaded", function() {
		var paral = new Parallax( "#site" );

	});

})();

Potete osservare l'esempio di seguito.

See the Pen Pure JavaScript parallax scrolling: the basics by Gabriele Romanato (@gabrieleromanato) on CodePen.

Torna su