htmlintermediatemitFeatured

GSAP Magnetic Button

A button that magnetically follows the cursor.

3.3k2.1k601491

About this module

A magnetic button built with GSAP quickTo for perfectly smooth cursor tracking.

#gsap#magnetic#cursor#button

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-zone">
      <button class="mh-mag">Get started</button>
    </div>
  2. 2

    Paste the script

    Include `script.js` after GSAP.

    const btn = document.querySelector(".mh-mag");
    const xTo = gsap.quickTo(btn, "x", { duration: 0.3, ease: "power3" });
    const yTo = gsap.quickTo(btn, "y", { duration: 0.3, ease: "power3" });
    btn.addEventListener("mousemove", (e) => {
      const r = btn.getBoundingClientRect();
      xTo((e.clientX - r.left - r.width / 2) * 0.3);
      yTo((e.clientY - r.top - r.height / 2) * 0.3);
    });
    btn.addEventListener("mouseleave", () => { xTo(0); yTo(0); });
Overview
Categoryanimations
Frameworkhtml
Difficultyintermediate
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