How to detect mouse position in JavaScript

Tracking mouse position is fundamental for creating interactive features like custom cursors, tooltips, drag-and-drop interfaces, and hover effects. As the creator of CoreUI with extensive JavaScript experience since 2000, I’ve implemented mouse tracking in numerous interactive dashboard components and UI elements. The most effective approach uses the mousemove event listener to capture real-time coordinate updates through clientX and clientY properties. This method provides precise tracking relative to the viewport for smooth interactive experiences.

Use the mousemove event listener with clientX and clientY properties to track mouse coordinates.

document.addEventListener('mousemove', function(event) {
    const x = event.clientX
    const y = event.clientY
    console.log(`Mouse position: x=${x}, y=${y}`)
})

This code adds a mousemove listener to the document that fires whenever the mouse moves. The event.clientX and event.clientY properties provide the horizontal and vertical coordinates relative to the viewport’s top-left corner. These coordinates update in real-time as the user moves the mouse, enabling precise position tracking for interactive features.

Best Practice Note:

This is the foundation we use in CoreUI interactive components for mouse-based interactions. For performance-sensitive applications, consider throttling the mousemove events to reduce the frequency of updates.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team