htmladvancedmit

Mouse Parallax

Layered elements parallax with the cursor.

4.5k701841231

About this module

Three layers drift at different depths as the mouse moves, creating a tactile 3D feel.

#gsap#parallax#mouse#layers

Source code

Installation

  1. 1

    Install GSAP

    Install the animation library with your package manager.

    npm install gsap
  2. 2

    Create the files

    Create `index.html`, `style.css` and `script.js` in the same folder.

  3. 3

    Paste the code

    Copy each file's source into its matching file.

  4. 4

    Run it

    Open `index.html` (or import the logic into your bundler setup).

Usage

  1. 1

    Copy the HTML

    Paste the markup where you need it.

    <link rel="stylesheet" href="style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
    <script src="script.js"></script>
    <div class="mh-par">
      <div class="mh-layer l1">⬤</div>
      <div class="mh-layer l2">▲</div>
      <div class="mh-layer l3">✦</div>
    </div>
  2. 2

    Paste the script

    Include `script.js` after GSAP.

    const par = document.querySelector(".mh-par");
    const layers = gsap.utils.toArray(".mh-layer");
    const strengths = [30, 55, 80];
    layers.forEach((layer, i) => {
      gsap.set(layer, {
        xPercent: -50, yPercent: -50,
        x: gsap.quickTo(layer, "x", { duration: 0.6, ease: "power3" }),
        y: gsap.quickTo(layer, "y", { duration: 0.6, ease: "power3" }),
      });
      layer._s = strengths[i];
    });
    par.addEventListener("mousemove", (e) => {
      const r = par.getBoundingClientRect();
      const nx = (e.clientX - r.left) / r.width - 0.5;
      const ny = (e.clientY - r.top) / r.height - 0.5;
      layers.forEach((layer) => {
        layer.x(nx * layer._s * 2);
        layer.y(ny * layer._s * 2);
      });
    });
Overview
Categoryanimations
Frameworkhtml
Difficultyadvanced
Licensemit
Versionv1.0.0
Features
  • Powered by GSAP
  • GPU-accelerated transforms
  • Pauseable timeline
Traits
  • ResponsiveYes
  • Dark modeYes
  • AccessibleYes
  • Production readyYes
Dependencies
gsap@^3.12
Browser support
  • Chrome 90+
  • Firefox 90+
  • Safari 15+
  • Edge 90+

Related modules

Command Palette

Search modules and jump anywhere