Parallax Scrolling #3 - jQuery

Introduction:

Welcome to the third and final part of Parallax Scrolling tutorial in HTML, CSS, and jQuery. This part is going to cover the jQuery part of the script, which handles the actual moving of the parallax effect.

Including jQuery:

Before we can begin writing a bit of jQuery, we must first include it in our HTML file. To do this, go to the official jQuery website; http://www.jquery.com/, click Download, and copy the CDN links;
  1. <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  2. <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
Then paste those within the 'head' tags of your HTML page. We are now ready to write some jQuery.

Writing the jQuery:

First create the basic Javascript tags within your 'head' tags of your HTML page... Now, we really are ready to write some jQuery. The basic method of how this is going to work, is; When the user scrolls, A basic maths calculation is made, The parallax content is positioned according to the above maths calculation result. So the first thing we need is to hook on to the document.scroll event. This will be activated each time the user scrolls the page...
  1. $(document).scroll( function() {
  2. });
Now that we have this, we want to perform an action to re-position the parallax content each time the user scrolls, so within that function we are going to call a function named 'parallax' which we are yet to create...
  1. $(document).scroll( function() {
  2. parallax();
  3. });
Now we need to create the 'Parallax' function. First we make the basic function structure...
  1. function parallax() {
  2. }
Next we want to grab the 'parallax' CSS class/HTML ID div element. This is because it's the element that we want to manipulate each time the user scrolls through the page...
  1. var layer = document.getElementById('parallax');
Finally, we want to use the above 'layer' object to set the 'parallax' div's position via a simple maths calculation...
  1. layer.style.top = -(window.pageYOffset / 2) + 'px';

Finished!

Feel free to mess around with the maths calculation to get a different speed, distance, or direction on the parallax effect.

Add new comment