Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Created December 19, 2016 10:35
Show Gist options
  • Save Anthodpnt/34f624e976f5ba29c007ba622c3111f5 to your computer and use it in GitHub Desktop.
Save Anthodpnt/34f624e976f5ba29c007ba622c3111f5 to your computer and use it in GitHub Desktop.
Misc - Parallax
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <antho.dpnt@gmail.com>
* @site: https://www.twitter.com/JsGists
*
* Another trendy effect you will find on many websites is Parallax. A parallax is created when to elements
* move at the same time but with different values. This is often used to create depth effects when the
* furthest element move more than the nearest element.
*
* Example:
* I have a composition of mountains and I want to add some depth in it when the mouse moves by adding some
* parallax effect.
**/
// First we select our images
const elements = document.querySelectorAll('img');
// We define some variables we will need later. 2 variables for the mouse position
// and 2 variables for our images positions.
let sx = 0;
let sy = 0;
let dx = sx;
let dy = sy;
// We bind a mousemove event to the window to update watch the mouse position.
window.addEventListener('mousemove', onMove);
function onMove(e) {
// We only update the mouse position variables and we substract half of the width
// and half of the height so the parallax value for our images will be 0 when the
// mouse will be at the center of the image.
sx = e.clientX - (window.innerWidth / 2);
sy = e.clientY - (window.innerHeight / 2);
}
// Then we start a `requestAnimationFrame` loop.
// For more informations about `requestAnimationFrame` check the episode #6 of
// "Gist for Javascript Beginners".
window.requestAnimationFrame(render);
function render() {
// We apply a parallax on each image base on it's index. The smaller the index is
// the smaller the parallax will be. This is not based on the `z-index` we set in CSS.
// The index here is the position of the image in the DOM tree. The first image as an
// index of 0, the second an index of 1, etc...
Array.prototype.forEach.call(elements, (el, index) => {
// We then calculate the parallax of each image by multiplying the mouse position by
// a random small value you choose and the index to get the effect you want. I also
// multiply by -1 to inverse the axis so if the mouse goes left, the parallax goes right, etc...
dx = sx * 0.003 * index * -1;
dy = sy * 0.001 * index * -1;
// Finally we apply the parallax to each image with a CSS3 transform.
el.style.transform = `translate(${dx}px, ${dy}px)`;
});
// And we loop again.
window.requestAnimationFrame(render);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment