Cursor · 19 of 22

Dot Grid Repel

Grid points flee from cursor

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="dot-grid-area" id="dotGridArea"></div>

CSS

.dot-grid-area {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-template-rows: repeat(8, 1fr);
  height: 240px;
  background: #12121a;
  overflow: hidden;
}

.grid-dot {
  width: 4px; height: 4px;
  background: #555;
  border-radius: 50%;
  margin: auto;
  transition: transform 0.2s ease-out;
}

JavaScript

var area = document.getElementById('dotGridArea');
var COLS = 10, ROWS = 8;
var RANGE = 60;     // px — repel radius
var STRENGTH = 0.5; // push per px inside the radius

for (var i = 0; i < COLS * ROWS; i++) {
  var d = document.createElement('div');
  d.className = 'grid-dot';
  area.appendChild(d);
}
var dots = area.querySelectorAll('.grid-dot');

area.addEventListener('mousemove', function (e) {
  var mx = e.clientX;
  var my = e.clientY;

  dots.forEach(function (dot) {
    var r = dot.getBoundingClientRect();
    var cx = r.left + r.width / 2;
    var cy = r.top + r.height / 2;
    var dist = Math.sqrt(Math.pow(mx - cx, 2) + Math.pow(my - cy, 2));

    if (dist < RANGE) {
      var angle = Math.atan2(my - cy, mx - cx);
      var force = (RANGE - dist) * STRENGTH;
      // Push away from the cursor (negative direction)
      var moveX = Math.cos(angle) * -force;
      var moveY = Math.sin(angle) * -force;
      dot.style.transform = 'translate(' + moveX + 'px, ' + moveY + 'px)';
    } else {
      dot.style.transform = 'translate(0, 0)';
    }
  });
});

area.addEventListener('mouseleave', function () {
  dots.forEach(function (d) { d.style.transform = 'translate(0, 0)'; });
});