Mouse events
Discover the basics of working with mouse events in JavaScript
See more on JavaScript events
When looking at mouse events we have the ability to interact with
mousedown
the mouse button was pressedmouseup
the mouse button was releasedclick
a click eventdblclick
a double click eventmousemove
when the mouse is moved over the elementmouseover
when the mouse is moved over an element or one of its child elementsmouseenter
when the mouse is moved over an element. Similar tomouseover
but does not bubble (more on this soon!)mouseout
when the mouse is moved out of an element, and when the mouse enters a child elementsmouseleave
when the mouse is moved out of an element. Similar tomouseout
but does not bubble (more on this soon!)contextmenu
when the context menu is opened, e.g. on a right mouse button click
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.
When inside an eventh 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:
altKey
true if alt key was pressed when the event was firedbutton
if any, the number of the button that was pressed when the mouse event was fired (usually 0 = main button, 1 = middle button, 2 = right button). Works on events caused by clicking the button (e.g. clicks)buttons
if any, a number indicating the button(s) pressed on any mouse event.clientX
/clientY
the x and y coordinates of the mouse pointer relative to the browser window, regardless of scrollingctrlKey
true if ctrl key was pressed when the event was firedmetaKey
true if meta key was pressed when the event was firedmovementX
/movementY
the x and y coordinates of the mouse pointer relative to the position of the last mousemove event. Used to track the mouse velocity while moving it aroundregion
used in the Canvas APIrelatedTarget
the secondary target for the event, for example when movingscreenX
/screenY
the x and y coordinates of the mouse pointer in the screen coordinatesshiftKey
true if shift key was pressed when the event was fired
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025