jQuery Parallax Scrolling Tutorial

Here I will show all that’s needed to achieve jQuery parallax scrolling using 3 image layers (this can easily be expanded to more layers) and a few lines of code. You can see the full DEMO or DOWNLOAD¬†the files.

I have 3 images: One solid background image and 2 transparent PNG’s to layer on top of the background at perceived differing closeness to the screen. To achieve the parallax scrolling effect, the background image should have the slowest speed, and the “closer” layers should move progressively faster. It’s just like when you are looking out the window of a car; The hill on the horizon moves by much slower¬†than that burning warehouse in the middle distance and trees on the side of the road fly by much quicker.

The logic is offensively simple. For every X pixels you scroll the window, with jQuery, you move the “nearest” layer 0.8 x X pixels, the middle layer at 0.5 x X pixels and the “furthest” layer 0.2 x X pixels. Of course, you can easily adjust these values to achieve different effects.

Here’s the HTML:

<div class="bgWrapper"></div>
<div class="shark"></div>
<div class="fish"></div>
<div class="mainWrapper"><!-- --></div>

The CSS:

.bgWrapper{
	position:fixed;
	background:url(underwater-bg.jpg) top center no-repeat; 
	height:100%; 
	width:100%; 
	top:0; 
	left:0;
}
.shark{
	position:fixed;
	background:url(shark.png);
	width:250px; 
	height:187px; 
	left:50%; 
	margin-left:-600px;
	margin-top:400px;
}
.fish{
	position:fixed;
	background:url(fish.png);
	width:300px;
	height:246px;
	left:50%;
	margin-left:400px;
	margin-top:500px;
}

..And the jQuery

$(document).ready(function(){
	$(window).bind('scroll',function(e){
   		parallaxScroll();
   	});
 
   	function parallaxScroll(){
   		var scrolledY = $(window).scrollTop();
		$('.bgWrapper').css('background-position','center -'+((scrolledY*0.2))+'px');
		$('.shark').css('top','-'+((scrolledY*0.5))+'px');
		$('.fish').css('top','-'+((scrolledY*0.8))+'px');
   	}
 
});

Want to hear me talk? I co-host the web development podcast “Three Devs and a Maybe”. Check us out here