Lenap Lenap - 6 months ago 130
Javascript Question

Rotate div to mouse position

I want to let a div rotate to the point where the mouse will be,

So when my mouse is left it have to show

<-
when my mouse is to the right it have to show
->


This needs to be in any direction!

Does anyone have a solution?

Answer

You can listen for mouse move events to get the position of the cursor. Then, use a rotation transform to make the arrow rotate.

var arrow = document.querySelector("#arrow");
var arrowRects = arrow.getBoundingClientRect();
var arrowX = arrowRects.left + arrowRects.width / 2;
var arrowY = arrowRects.top + arrowRects.height / 2;

addEventListener("mousemove", function(event) {
    arrow.style.transform = "rotate(" + Math.atan2(event.y - arrowY, event.x - arrowX) + "rad)";
});
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
<div id="arrow">&gt;</div>

Comments