JSFiddle - React, Tailwind, and code Playground

arrow follows mouse

by Travis Almand

HTML

<div id="container"><div id="arrow"></div></div>

CSS

:root {
  --angle: 0deg;
  --x: 0;
  --y: 0;
}

body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#container {
  bottom: 0;
  height: 40px;
  left: 0;
  margin: auto;
  position: absolute;
  right: 0;
  top: 0;
  //transform: translate3d(var(--x), var(--y), 0);
  //transition: transform 1s;
  width: 20px;
}
#arrow {
  border-style: solid;
  border-width: 20px 0 20px 20px;
  border-color: transparent transparent transparent gainsboro;
  height: 0;
  transform: rotate3d(0, 0, 1, var(--angle));
  transition: transform 0.1s;
  width: 0;
}

JavaScript

var $arrow = document.querySelector('#arrow');
var arrowLoc = {x: $arrow.getBoundingClientRect().left, y: $arrow.getBoundingClientRect().top};
var mouseLoc = {x: 0, y: 0};
var angle;
var moveToX = 0;
var moveToY = 0;

document.addEventListener('mousemove', function (e) {
  mouseLoc = {x: e.clientX, y: e.clientY};
  
	angle = Math.atan2(mouseLoc.y - arrowLoc.y, mouseLoc.x - arrowLoc.x) * 180 / Math.PI;
  
  if (mouseLoc.x < arrowLoc.x) {
  	moveToX = -(arrowLoc.x - mouseLoc.x);
  } else {
  	moveToX = mouseLoc.x - arrowLoc.x;
  }
  
  if (mouseLoc.y < arrowLoc.y) {
  	moveToY = -(arrowLoc.y - mouseLoc.y);
  } else {
  	moveToY = mouseLoc.y - arrowLoc.y;
  }
  
  document.documentElement.style.setProperty('--angle', angle + 'deg');
  document.documentElement.style.setProperty('--x', moveToX + 'px');
  document.documentElement.style.setProperty('--y', moveToY + 'px');
  
  //console.log({arrowLoc});
  //console.log({mouseLoc});
});