8

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?

EDIT:

<style>
    body {
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
    }
</style>

<div id="arrow">&gt;</div>

<script type="text/javascript">
    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)";
    });
</script>

2 Answers 2

16

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

function getCenter(element) {
    const {left, top, width, height} = element.getBoundingClientRect();
    return {x: left + width / 2, y: top + height / 2}
}

const arrow = document.querySelector("#arrow");
const arrowCenter = getCenter(arrow);
addEventListener("mousemove", ({clientX, clientY}) => {
    const angle = Math.atan2(clientY - arrowCenter.y, clientX - arrowCenter.x);
    arrow.style.transform = `rotate(${angle}rad)`;
});
html  {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
<div id="arrow">&gt;</div>

3
  • I dont get it, it works in jsfiddle, but not in my localhost...?
    – user4640949
    May 16, 2016 at 19:22
  • Make sure the script is run after the element is loaded by putting the script tag right at the end of the body.
    – metarmask
    May 16, 2016 at 19:24
  • Did you use the same browser when you viewed localhost? Just discovered Firefox doesn't support the x and y alias yet. When I changed that the code you put in the question works in both Firefox and Chrome.
    – metarmask
    May 16, 2016 at 19:39
2

A jQuery version of metarmask's answer.

var arrow = $('#arrow');
var arrowX = arrow.offset().left + arrow.outerWidth(true) / 2;
var arrowY = arrow.offset().top + arrow.outerHeight(true) / 2;

$(document).on('mousemove', function(event) {
  var rad = Math.atan2(event.pageY - arrowY, event.pageX - arrowX);
  arrow.css('transform', 'rotate('+rad+ 'rad)');
});
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="arrow">&gt;</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.