YouTip LogoYouTip

Event Mousemove

## jQuery mousemove() Method The `mousemove()` method in jQuery is used to trigger the `mousemove` event or attach an event handler to run when the mouse pointer moves within a specified element. --- ### Introduction The `mousemove` event occurs every time the mouse pointer moves by even a single pixel inside the selected element. Because this event fires continuously as the mouse moves, it is highly useful for tracking real-time coordinates, creating drag-and-drop interfaces, rendering custom cursors, or drawing on canvas elements. --- ### Syntax #### 1. Trigger the mousemove event manually To trigger the `mousemove` event on selected elements: ```javascript $(selector).mousemove() ``` #### 2. Bind an event handler to the mousemove event To attach a function that executes when the mouse moves inside the selected element: ```javascript $(selector).mousemove(handler) ``` #### Parameter Details | Parameter | Type | Description | | :--- | :--- | :--- | | `handler` | `Function` | Optional. A function to execute each time the `mousemove` event is triggered. It receives an event object containing details like pointer coordinates. | --- ### Code Examples #### Example 1: Tracking Mouse Coordinates on the Page The following example tracks the real-time coordinates of the mouse pointer relative to the document and displays them inside a `` element. ```javascript $(document).ready(function(){ $(document).mousemove(function(event){ // event.pageX and event.pageY retrieve the X and Y coordinates of the mouse $("span").text("X: " + event.pageX + ", Y: " + event.pageY); }); }); ``` #### Example 2: Hover Effects and Coordinate Tracking inside a Specific Box You can also restrict coordinate tracking to a specific container, such as a `div`. ```html
Move your mouse inside this box.

Coordinates: 0, 0

``` --- ### Performance Considerations > ⚠️ **Important Performance Warning:** > The `mousemove` event fires repeatedly and rapidly (potentially dozens of times per second) as the user moves the mouse. Binding heavy computations, complex DOM manipulations, or API calls directly to this event can severely degrade browser performance and cause UI lag. #### Best Practices for `mousemove`: 1. **Keep Handlers Lightweight:** Ensure the code inside the `mousemove` callback is as simple and fast as possible. 2. **Throttling and Debouncing:** If you need to perform expensive operations (like updating complex layouts), use throttling or debouncing techniques (e.g., via Lodash or `requestAnimationFrame`) to limit how often the handler executes. 3. **Unbind When Done:** If you only need to track movement during a specific action (like a drag-and-drop operation), bind the `mousemove` event on `mousedown` and unbind it using `.off("mousemove")` on `mouseup`.
← Event OffEvent Mouseleave β†’