Cheesetoast

Brain Food for Web Developers

Up and down arrow

Simple Lightweight Parallax Scrolling Background

I recently incorporated the parallax scrolling effect into a page and I wanted to share the code for it. I’ve seen some pretty sophisticated jQuery plugins that offer some neat options but this is just a simple lightweight version. Parallax scrolling is about making the background image move at a different rate than the foreground image to create the illusion of depth. This is achieved by using javascript to detect the user’s scroll position and dynamically change the background image position accordingly through CSS.


See the Pen Parallax Scrolling Snow by Graham Clark (Cheesetoast) on CodePen

Let’s start with some basic HTML:

<body id="parallax">
  <section>
    <!-- Content goes here -->
  </section>
</body>

CSS (can be applied to divs also):

html {
  background-image: url(background-image.jpg);
}

body {
  background-image: url(transparent-image.png);
  background-repeat: repeat-x; // Optional
}

Javascript:

<script>
var parallax = document.getElementById("parallax");
var speed = -1;

window.onscroll = function() {
  var yOffset = window.pageYOffset;
  parallax.style.backgroundPosition = "0px " + (yOffset / speed) + "px";
}
</script>

Hope you like it!

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.