Move button randomly on hover: Javascript

Viewed 1038

I have a button that I want to move randomly on hover. I want it to be able to move anywhere not pseudorandom, but truly random. The code I have only made the button go to the bottom right.

Also, if possible, if you could make an animation to make the animation smooth, that would be greatly appreciated.

document.addEventListener("mouseover", function (event) {
    x = event.pageX;
    y = event.pageY;
    div.style.left = x + 35 + "px";
    div.style.top = y + 35 + "px";
});
1 Answers

Add an event listener for mouseover, then generate random coordinates by using Math.random() multiplied by Window.innerHeight and Window.innerWidth:

$('button').on('mouseover', function() {
  $(this).css({
    'top': Math.random() * window.innerHeight + "px",
    'left': Math.random() * window.innerWidth + "px"
  });
})
button {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Try to click me!</button>

To make it smooth, we can use jQuery's animate() function:

$('button').on('mouseover', function() {
  $(this).animate({
    'top': Math.random() * window.innerHeight + "px",
    'left': Math.random() * window.innerWidth + "px"
  }, "medium");
})
button {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Try to click me!</button>

Related