Mouse Events

Learn how to control mouse events.

Mouse events

There’s a number of events that relate to the mouse pointer and its interactions with elements on the page.

Mouse move

Every time the mouse pointer moves, the mousemove event fires. To see an example of this, we’ll write some code that tells us the coordinates of the mouse pointer whenever it moves.

Let’s add the following event listener in the index.js file:

document.addEventListener('mousemove', showCoords);

This will call the showCoords function whenever the mouse pointer moves anywhere on the page. Let’s write that function now:

Press + to interact
function showCoords(event) {
document.body.textContent = `(${event.x},${event.y})`;
}

This function updates the textContent property of the document body to contain the coordinates of the mouse pointer. The x and y properties of the event object tell us the horizontal and vertical position of the mouse pointer respectively. We can use a template literal to insert these values into the text content of the document’s body every time the mouse moves. Try moving the mouse pointer around on the page and you should see its exact coordinates displayed in the top left corner.

Mouse over

The mouseover event is fired when the mouse pointer moves over an element. To see this in action, ...