Parallax scrolling is a unique technique wherein a background image will move slower than the foreground image which create a 2D illusion.

There are lots of methods to create a parallax scrolling where some programmers jumped into complex techniques with bunch of JavaScript codes to achieve the best parallax effect.

Today, I will show you how to create a simple parallax effect using jQuery.

The logic is very simple. We will control the background position of the background image. Using jQuery, we will change the position of the background image using the page scrolling offset. We will set the background position of the image in every page scroll, those will result a slower movement of the background image.

The HTML

Assuming that the html tag below has content in it.

<div class="parallax">
	...
</div>

The CSS

Lets set the background properties of the parallax container. Lets add a bigger padding to show more of our background image.

.parallax {
    background-size: cover;
    background-repeat: no-repeat;
	background-attachment: fixed;
    background-image: url("cat.jpg");
    padding: 100px 0;
}

The jQuery

Since the script is dependent with jQuery, we need to include the jQuery library into the page template.

<head>
	...
	<script src="jquery.js"></script>
</head>

Finally, paste the script below (inside the <script> tag or into your JavaScript template) that will set the background position of our background image in every page scroll.

jQuery(function($) {
	$(window).scroll(function() {
		//lets get the scroll offset
		var scrolltop = $(window).scrollTop();

		if ( $(".parallax").length ) {
			//lets set the x-axis into 50% which will center the image in x-axis
			//lets use the scrolltop value as the y-axis position of the image
			$(".parallax").css("backgroundPosition", "50% " + -(scrolltop/6) + "px");
		}
	});
});

Open the demo link below to see our parallax in action.