Interactive Multi-layer Parallax Effect With JavaScript

Category: Animation , Javascript | September 2, 2022
Author:Albinaaaaa
Views Total:18 views
Official Page:Go to website
Last Update:September 2, 2022
License:MIT

Preview:

Interactive Multi-layer Parallax Effect With JavaScript

Description:

A slick multi-layer parallax effect that interacts with cursor movement. Built on top of JavaScript and CSS transforms.

How to use it:

1. Add parallax elements to the page and define the speed of the parallax effect using the data-speed attribute:

<div data-speed="10" class="layer layer--1">
  Element 1
</div>
<div data-speed="20" class="layer layer--2">
  Element 2
</div>
<div data-speed="30" class="layer layer--3">
  Element 3
</div>
...

2. Make the layers absolutely positioned.

.layer {
  position: absolute;
}
.layer--1 {
  top: 10%;
  left: 20%;
}
.layer--2 {
  top: 45%;
  right: 10%;
}
.layer--3 {
  bottom: 15%;
  left: 43%;
}
...

3. The main JavaScript to enable the interactive parallax effect.

function parallax(event) {
  console.log(event);
  this.querySelectorAll(".layer").forEach((layer) => {
    let speed = layer.getAttribute("data-speed");
    layer.style.transform = `translate(${(event.clientX * speed) / 1000}px, ${
      (event.clientY * speed) / 1000
    }px)`;
  });
}
document.addEventListener("mousemove", parallax);

You Might Be Interested In:


Leave a Reply