SpinSpire logo

Creating the parallax effect using Javascript and CSS

The parallax effect, or scrolling parallax effect, has become popular on modern websites. My favorite example of the parallax effect is implemented on http://boy-coy.com/. You may be thinking to yourself that this looks difficult to implement, but actually it's incredibly easy. The most difficult part will be creating the images and deciding how to make them move and work together.

Programming the movement itself is very easy. They simply run on one mechanic, event listeners bound to the mouse scroll. All the event listeners do is invert the mouse scroll direction and divide to make it move slower. Dividing by 4 means your parallax image will move four time slower than your mouse scroll speed. So, when you scroll down the image will scroll up the page at a set rate. You can get more advanced to make them move left or right and make them appear to interact with each other.

Below is the simplest example I made. The implementation may be found at http://legacy.jordanmclemore.com/labs/1.html. You'll notice each parallax images is positioned as a background at a location. Each images is controlled by it's own controller and function called by the controller.
 

CSS:

body {
  margin: 0px; 
  background: url(bg.jpg) fixed;
}

#prlx_lyr_1 {
  position: fixed;
  background: url(parallax_bg1.png) no-repeat 0px 500px;
  width: 100%;
  height: 1200px;
}

#prlx_lyr_2 {
  position: fixed;
  background: url(parallax_bg1.png) no-repeat 300px 200px;
  width: 100%;
  height: 1200px;
}

#prlx_lyr_3 {
  position: fixed;
  background: url(parallax_bg1.png) no-repeat 400px 700px;
  width: 100%;
  height: 1200px;
}

#content_layer {
  position: absolute;
}

JavaScript:  

<script>

function parallax() {
  var prlx_lyr_1 = document.getElementById('prlx_lyr_1');
  prlx_lyr_1.style.top = -(window.pageYOffset / 8)+'px';
}

function parallax2() {
  var prlx_lyr_2 = document.getElementById('prlx_lyr_2');
  prlx_lyr_2.style.top = -(window.pageYOffset / 5)+'px';
}

function parallax3() {
  var prlx_lyr_3 = document.getElementById('prlx_lyr_3');
  prlx_lyr_3.style.top = -(window.pageYOffset / 2)+'px';
}

window.addEventListener("scroll", parallax, false);
window.addEventListener("scroll", parallax2, false);
window.addEventListener("scroll", parallax3, false);

</script>

 


tags: Knowledge Base javascript css web development