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');
   	}
 
});
Did you like this post? Why not subscribe?

11 thoughts on “jQuery Parallax Scrolling Tutorial

  1. Pingback: jQuery Sprite Animation - Simple Tutorial

    • No Problem.

      I’m not sure I follow the question. There is no “animation” going on in this tutorial per se. We are just moving the position of the various elements in relation to the scroll to achieve the parallax effect. Were you maybe referring to the sprite animation tutorial?

      Let me know if you need some more help.

    • You can yes, you just need to adjust the css(‘left’) or css(‘margin-left’) in the parallaxScroll() function rather than the ‘top’ property.
      Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>