Today I will show you how you can apply parallax effect to every website with tiled background.

VIEW DEMO DOWNLOAD FILES

The idea behind the effect is to to move the background and offsetting it while the page is scrolled. The different movement distance of the content and the background will create the nifty parallax effect.  We will be using jQuery  to track the page scrolling and to move the background. Let’s start with declaring variables we’ll need later:

$(function(){
   var $window = $(window);
   var $body = $("body").css("background-attachment" , "fixed");
   var scrollAmount = -2;
 });

 

First, we need to make sure that our code runs after the page DOM is loaded, so we’re executing it on jQuery ready() function. After this we declare the variables – caching the window, the body, setting the body background-attachment css property to fixed and create a new variable called scrollAmount that will help us calculate the background movement.

Next, we need to execute function every time the page is scrolled and then, to calculate and set the background position in this function.

$window.scroll(function() {
    //code here will run every time we're scrolling 
});

Finally, we need to calculate the new background position and set body’s background to this new position.

$body.css("background-position", "center " + parseInt( $window.scrollTop()/scrollAmount ) + "px");

We’re ready! To reverse the scroll, just set the scrollAmount to positive number.

Here’s the full code:

$(function(){

	//caching window and body, setting the body background attachment to fixed
	var $window = $(window);
	var $body = $("body").css("background-attachment" , "fixed");

	//scroll amount - the less it is, the more noticable the effect is 
	var scrollAmount = -2;

	//functuon executed while we're scrolling 
	$window.scroll(function() {
		//moving the background position 
                $body.css("background-position", "center " + parseInt( $window.scrollTop()/scrollAmount ) + "px");
         });		

});

One line version :

$(window).scroll(function() { $("body").css("background-position", "center " + parseInt( $(this).scrollTop()/-2 ) + "px");  });

Next time I will show you how to create fullscreen background effect.