JavaScript mousemove
The mousemove
event in JavaScript is fired when the mouse pointer is moved over an element. This event can be used to trigger a function or code block that responds to the mouse movement.
Syntax
element.addEventListener('mousemove', function(event) {
// code to be executed
});
Example
<div id="box"></div>
<script>
const box = document.getElementById('box');
box.addEventListener('mousemove', function(event) {
console.log(`Mouse position: (${event.clientX}, ${event.clientY})`);
});
</script>
Output
As the mouse is moved over the box
element, the mousemove
event is triggered and the console logs the current mouse position.
Mouse position: (203, 115)
Mouse position: (250, 240)
Mouse position: (34, 304)
...
Explanation
In the example above, we use document.getElementById
to select the box
element and attach a mousemove
event listener to it using addEventListener
. The function we pass to addEventListener
is executed every time the mouse is moved over the element.
Within the mousemove
event function, we can access information about the mouse position using the event
parameter. In this example, we log the X and Y coordinates of the mouse cursor to the console using event.clientX
and event.clientY
.
Use
The mousemove
event can be used to create interactive features on web pages. For example, we could use it to update the position of an object on the screen in response to the mouse movement, or to trigger a visual effect when the cursor hovers over a particular element.
Important Points
- The
mousemove
event is fired whenever the mouse is moved over an element. - The
event
parameter provides information about the mouse position, which can be used to trigger actions and events. - The
mousemove
event can be attached to any element on a webpage.
Summary
The mousemove
event in JavaScript is triggered when the mouse is moved over an element. It can be useful for creating interactive features on web pages and responding to user input. By using the event
parameter, we can access information about the mouse position, which can be used to trigger a range of actions and events.