onmousemove

The onmousemove attribute is triggered when the pointer moves over an element. It activates whenever the cursor is moved within the boundaries of that element.

onmousemove event

The onmousemove event occurs when the mouse pointer moves within an element. It's commonly used to monitor user actions or create interactive effects in web interfaces.

Syntax

In HTML

index.html
<element onmousemove="myScript">

In JS

script.js
object.onmousemove = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("mousemove", myScript);

Example

::event-onmousemove ::
index.html
<!DOCTYPE html>
<html>
<style>
div {
  width: 200px;
  height: 100px;
  border: 1px solid black;
}
</style>

<body>
<h1>HTML DOM Events</h1>
<h2>The onmousemove Event</h2>

<div onmousemove="myFunction(event)" onmouseout="clearCoor()"></div>

<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>

<p>When the mouse is moved over the div, the p element will display the horizontal and vertical coordinates of your mouse pointer, whose values are returned from the clientX and clientY properties on the 
MouseEvent object.</p>

<p id="demo"></p>

<script>
function myFunction(e) {
  let x = e.clientX;
  let y = e.clientY;
  let coor = "Coordinates: (" + x + "," + y + ")";
  document.getElementById("demo").innerHTML = coor;
}

function clearCoor() {
  document.getElementById("demo").innerHTML = "";
}
</script>

</body>
</html>

Values

  • <script>
    • Refers to the code that runs when the event is triggered.

Conclusion

The onmousemove event is useful for tracking mouse movement and creating interactive elements in web development. By linking a <script> to the event, developers can respond dynamically to user actions. It offers a powerful way to enhance user experience through real-time feedback.