This code snippet enables a parallax effect on a webpage based on mouse movement. It adds “mousemove” event listener to the document and trigger parallax
function. Inside the function, it calculates the position of the mouse relative to the window’s dimensions. It then applies different depths of parallax effect to the background position of an element with the ID “parallax”.
The _depth1
, _depth2
, and _depth3
variables control the amount of movement in different layers of the parallax effect. The resulting positions are set as the background position of the element using CSS, creating a visually appealing parallax effect.
How to Create Parallax Effect using CSS & Mouse Movement
1. Create a div element with an id “parallax” and add your content inside it.
<div id="parallax"><h1>Parallax</h1></div>
2. Use the following CSS code to style the parallax effect.
body{ margin: 0; background-color: #1d1e22 !important; } #parallax { position: relative; width: 100%; height: 100vh; background-image: url(https://raw.githubusercontent.com/oscicen/oscicen.github.io/master/img/depth-3.png), url(https://raw.githubusercontent.com/oscicen/oscicen.github.io/master/img/depth-2.png), url(https://raw.githubusercontent.com/oscicen/oscicen.github.io/master/img/depth-1.png); background-repeat: no-repeat; background-position: center; background-position: 50% 50%; } h1 { position: absolute; top: 47%; left: 50%; transform: translate(-50%, -50%); color: #fff; font-family: "Arial"; text-transform: uppercase; opacity: .2; font-size: 70px; }
3. Finally, add the following JavaScript function to your project to activate parallax effect:
(function() { // Add event listener document.addEventListener("mousemove", parallax); const elem = document.querySelector("#parallax"); // Magic happens here function parallax(e) { let _w = window.innerWidth/2; let _h = window.innerHeight/2; let _mouseX = e.clientX; let _mouseY = e.clientY; let _depth1 = `${50 - (_mouseX - _w) * 0.01}% ${50 - (_mouseY - _h) * 0.01}%`; let _depth2 = `${50 - (_mouseX - _w) * 0.02}% ${50 - (_mouseY - _h) * 0.02}%`; let _depth3 = `${50 - (_mouseX - _w) * 0.06}% ${50 - (_mouseY - _h) * 0.06}%`; let x = `${_depth3}, ${_depth2}, ${_depth1}`; console.log(x); elem.style.backgroundPosition = x; } })();
That’s all! hopefully, you have successfully created a parallax effect using CSS and mouse movement events. If you have any questions or suggestions, feel free to comment below.