Simple Background Parallax Scrolling with Pure JavaScript

Category: Animation , Javascript | June 2, 2015
Author: everydayhero
Views Total: 3,789
Official Page: Go to website
Last Update: June 2, 2015
License: MIT

Preview:

Simple Background Parallax Scrolling with Pure JavaScript

Description:

A pure JavaScript implementation of a simple parallax scrolling effect for background images.

How to use it:

Load the necessary JavaScript file in your project.

<script src="parallaxScrolling-1.0.min.js"></script>

Add a parallax scrolling area to your webpage.

<div id="demo"></div>

The required CSS styles.

#banner {
  ...
  
  background-size: cover;
  transition: background-position 0.05s linear;
}

Pass the parameters to the parallax scrolling effect.

// ID of DOM element.
var id = "demo";

// Source of background image.
var src = bg.jpg; 

// Scroll direction can be either "down" or "up". 
var scrollDir = "down";

// Max number of pixels the background can move vertically. 
var maxOffset = "auto";

Initialization.

var parallax = new Parallax();
parallax.init(id, src, scrollDir, maxOffset);
var el = document.getElementById(id);

Event listeners.

function parallaxLoad() {
  el.style.backgroundPosition = ('0 '+parallax.scroll()+'px');
}
window.addEventListener('scroll', function() {
  el.style.backgroundPosition = ('0 '+parallax.scroll()+'px');
});
window.addEventListener('resize', function() {
  el.style.backgroundPosition = ('0 '+parallax.resize()+'px');
});

You Might Be Interested In:


Leave a Reply