This code tracks the movement of the mouse using the mousemove event, which runs every time the mouse moves on the page. JavaScript provides the mouse position through the event object, where clientX gives the horizontal position and clientY gives the vertical position. These values are stored in variables and then displayed on the page by updating the text content of a paragraph element using DOM manipulation.
<!DOCTYPE html> <html> <body> <!-- Paragraph to show mouse position --> <p id="position">Move your mouse</p> <!-- Link JavaScript --> <script src="script.js"></script> </body> </html>
// Detect mouse movement
document.addEventListener("mousemove", function(event) {
// Get horizontal mouse position
let x = event.clientX;
// Get vertical mouse position
let y = event.clientY;
// Display mouse coordinates
document.getElementById("position").innerText =
"X: " + x + " , Y: " + y;
});