• We just launched and are currently in beta. Join us as we build and grow the community.

Parallax Scrolling #3 - jQuery

fadfad

Embedded Systems Coder
F Rep
0
0
0
Rep
0
F Vouches
0
0
0
Vouches
0
Posts
175
Likes
88
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 100 XP
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...

  1. <script

    >
  2. </

    script

    >

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.


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

338,631

338,639

Top