CSS transitions can be applied to a wide variety of scenarios, including a basic implementation of a parallax scrolling entirely handled by JavaScript. No jQuery required.
The first thing we need to do is to use the transition
property on the main wrapper element:
#site {
width: 100%;
position: relative;
transition: all 800ms ease-in;
top: 0;
}
Now JavaScript: we have a series of navigation links:
<nav id="navigation">
<a href="#home">Home</a>
<a href="#section-1">Section 1</a>
<a href="#section-2">Section 2</a>
</nav>
Each link contains the ID of its corresponding section in the form of an hash ( #section
). We need to get the current's section top offset
and modify the top
property of the main wrapper accordingly:
(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" );
});
})();
You can see the demo below.
See the Pen Pure JavaScript parallax scrolling: the basics by Gabriele Romanato (@gabrieleromanato) on CodePen.