How to create a simple parallax with jQuery in 3 minutes!

Medium 4202299 photo credit: Daveybot via photopin cc

Good evening, this is Bono.

I was working on a website and implemented parallax for the first time.
It is surprisingly easy and at once makes the site richer, so it will come in handy from now on.

Now, memo memo.

This is the only implementation.

For example, if you wanted to have three layers, you could write the following.

hypertext markup language

Nest three elements.

<div id="content-bottom">
<div id="content-middle">
<div id="content-top">
    <h1 class="hoge">例えばここにメッセージを書く</h1>
</div>
</div>
</div>

CSS

Set a background image for each. repeat-y may or may not be necessary depending on what you want to create.
If the content is long vertically and you want to use a continuous background, repeat-y is required.

#content-bottom {
    background: url(../img/bottom.png) repeat-y fixed center 0;
}
#content-middle {
    background: url(../img/middle.png) repeat-y fixed center 0;
}
#content-top {
    background: url(../img/top.png) repeat-y fixed center 0;
}

JavaScript

Each time scrolling occurs, the parallax function is called to obtain the scroll amount in the parallax function.
The amount of shift of the background image is determined according to that amount.
The amount of shift can then be changed for each background image.

var parallax = function(){
    var st = $(window).scrollTop();
    $('#content-img-3').css({
        backgroundPosition: 'center ' + Math.floor(-st/10) +'px'
    });
    $('#content-img-2').css({
        backgroundPosition: 'center ' + Math.floor(-st/5) +'px'
    });
    $('#content-img-1').css({
        backgroundPosition: 'center ' + Math.floor(-st/2.5) +'px'
    });
}

parallax();
$(window).scroll(function(){
    parallax();
});

The trick is.

  • The background image must be transparent or the image behind it will be hidden, thus creating no parallax. Images should be created in PNG or JPEG format, where transparency is possible.

  • Transparency is reduced a little + Image is made a little smaller
    This way, objects in the back appear more three-dimensional and distant. This is recommended.

Reference Books

The contents were adapted from the following book.
It was very easy to understand because it explained how to create parallax with diagrams. (P.193-196 is recommended).