Mouse events

By

Learn the basics of mouse events in JavaScript, from mousedown, mouseup, and click to mousemove, plus event properties like button and clientX you can read.

~~~

See more on JavaScript events

When looking at mouse events we have the ability to interact with

Events overlap. When you track a click event, it’s like tracking a mousedown followed by a mouseup event. In the case of dblclick, click is also fired two times.

mousedown, mousemove and mouseup can be used in combination to track drag-and-drop events.

Be careful with mousemove, as it fires many times during the mouse movement. We need to apply throttling, which is something we’ll talk more when we’ll analyze scrolling.

Prefer Pointer Events for new code

For new work, prefer Pointer Events. They are Baseline widely available. One set of listeners covers mouse, touch, and pen.

The names mirror the mouse ones:

Mouse events still fire when the pointer is a mouse. So old mouse* handlers keep working. If you write new interaction code, start with pointer* so you do not need a separate touch path.

When inside an event handler we have access to lots of properties.

For example on a mouse event we can check which mouse button was pressed by checking the button property of the event object:

const link = document.getElementById('my-link')
link.addEventListener('mousedown', (event) => {
  // mouse button pressed
  console.log(event.button) //0=left, 2=right
})

Here are all the properties we can use:

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about platform: