Step 9
Add another script tag and insert the standard JQuery ‘when the page is ready’ function - $(document).ready(function() . All of our JQuery code will sit inside this function.

The JQuery API website at api.jquery.com, is an excellent resource for syntax and example code.



Step 10
We need to track the position of the mouse when it moves over the viewport <div>. We can do this using the mousemove() function that’s built into JQuery. Add the code below inside your JQuery function to grab the mouse position relative to the <div>:


$(“#viewport”).mousemove(function(e) {
-- newX = (e.pageX- $(“#viewport”).offset().left);
-- newY = (e.pageY- $(“#viewport”).offset().top);
});



Step 11
Add in an extra line beneath the newY = line and enter the code below to test that you’re getting the correct X and Y coordinates. As you move your mouse over the <div> you should get values between 0 and 960 on the X axis, and 0 and 600 on the Y axis. When you’ve done testing, remove the line again.


alert(“X: “+newX+”:Y:”+newY);



Step 12
We need to act on the X and Y positions, translating them into a movement for each of the layers within the viewport.

The range of movement possible for each layer is dictated by the size of that layer, so we express the amount of movement as a percentage of the size difference between the viewport and the layer we want to move. We then move the layer that amount by changing its top and left position.

We need to know the width and height of the viewport, and the width and height of the layer we’re moving and, finally, we need to repeat this for each layer that should be moved. The JQuery each() function allows us to do that by selecting every layer with a class of “moveme”.



Step 13
Having established the theory, add the code contained within the 'Step 13' file to enable movement based on mouse position.



Step 14
Save your page and test it in your browser. You should now have a fully functioning parallax scrolling page. Observe how the movement gives the impression of depth, and that the bigger the layer, the more it moves.

From here, we need to tweak the aesthetics to suit our intentions, so make a note of where the movement appears
to be over-the-top or too subtle.



Step 15
Adjust the width and height of the different layers in the stylesheet, and resave them from your source image if necessary, to suit and alter the impact of the parallax scrolling.

This function can be used on a viewport of any size; just make sure to set the viewportwidth and viewportheight variables, and ensure that any layer that should move has the class=”moveme” attribute applied.


Who: Sam is an illustrator and graphic designer living in Scotland. He lectures, writes and illustrates, and loves typography.
Contact: hampton-smith.com
Software: Adobe Dreamweaver, Adobe Illustrator and JQuery Library
Time to complete: 30-60 minutes
On the CD or download: Files for this tutorial can be found on the cover CD or downloaded here