The Zelax The Zelax - 4 months ago 7
Javascript Question

How to make image change color while mouse is moving over?

First off, sorry for the weird title, I don't really know a better way of describing it.

Basically I want the image to change color while the mouse is moving (hovering) over it, but for it to stop when the mouse is still,

While the mouse is stationary, color doesn't change,

While the mouse is moving, color changes.

I know there is the hover attribute in CSS, but it only has 2 states, when the mouse is hovering over it, and when it is not, what i'm looking for is something a bit trickier.

Hopefully that explains it :/

Answer

Please try this:

document.getElementById("myDiv").onmousemove = function() {
  //Set random background color
  myDiv.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}

Demo:

document.getElementById("myDiv").onmousemove = function() {
  //Set random background color
  myDiv.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}
#myDiv {
  width: 150px;
  height: 150px;
  background-color: #ccc;
  text-align: center;
  line-height: 140px;
}
<div id="myDiv">Hover ME !</div>