Skip to content

Instantly share code, notes, and snippets.

@RezaAmd
Created January 22, 2022 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RezaAmd/874a96a8ca08a894bd30446517c740dd to your computer and use it in GitHub Desktop.
Save RezaAmd/874a96a8ca08a894bd30446517c740dd to your computer and use it in GitHub Desktop.
Javascript parallax library on mouse move.
// js:
class Parallax {
constructor(
parallax,
depthAttribute = "data-depth",
isSameDirectionAttribute = "data-same-direction"
) {
Array.from(parallax.querySelectorAll("[" + depthAttribute + "]")).forEach(
function (element) {
parallax.addEventListener(
"mousemove",
(event) => {
element.style.transition = "0s";
let isSameDirection = element.getAttribute(isSameDirectionAttribute)
? element.getAttribute(isSameDirectionAttribute) == 'true' ? true : false : false;
let x =
Math.floor(
(event.clientX - parallax.offsetWidth / 2) *
((element.getAttribute(depthAttribute) * 100) /
parallax.offsetWidth)
) * (isSameDirection == false ? -1 : 1);
let y =
Math.floor(
(event.clientY - parallax.offsetHeight / 2) *
((element.getAttribute(depthAttribute) * 100) /
parallax.offsetHeight)
) * (isSameDirection == false ? -1 : 1);
element.style.transform = "translate(" + x + "px," + y + "px)";
},
false
);
parallax.addEventListener(
"mouseleave",
(event) => {
element.style.transform = "none";
element.style.transition = "0.5s";
});
});
}
}
// How to use?
var example = document.getElementById("parallax-sample");
var parallaxInstance = new Parallax(example);
// in Html:
//<div id="parallax-sample">
// <img data-depth="0.2" data-same-direction="true" src="..." />
// <img data-depth="1" data-same-direction="flse" src="..." />
//</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment