Created
January 22, 2022 21:51
-
-
Save RezaAmd/874a96a8ca08a894bd30446517c740dd to your computer and use it in GitHub Desktop.
Javascript parallax library on mouse move.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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