When looking at mouse events we have the ability to interact with
mousedownthe mouse button was pressedmouseupthe mouse button was releasedclicka click eventdblclicka double click eventmousemovewhen the mouse is moved over the elementmouseoverwhen the mouse is moved over an element or one of its child elementsmouseenterwhen the mouse is moved over an element. Similar tomouseoverbut does not bubble (more on this soon!)mouseoutwhen the mouse is moved out of an element, or when the mouse enters a child elementmouseleavewhen the mouse is moved out of an element. Similar tomouseoutbut does not bubble (more on this soon!)contextmenuwhen 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 about when we’ll analyze scrolling.
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:
altKeytrue if alt key was pressed when the event was firedbuttonif 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)buttonsif any, a number indicating the button(s) pressed on any mouse event.clientX/clientYthe x and y coordinates of the mouse pointer relative to the browser window, regardless of scrollingctrlKeytrue if ctrl key was pressed when the event was firedmetaKeytrue if meta key was pressed when the event was firedmovementX/movementYthe 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 aroundregionused in the Canvas APIrelatedTargetthe secondary target for the event, for example when movingscreenX/screenYthe x and y coordinates of the mouse pointer in the screen coordinatesshiftKeytrue if the shift key was pressed when the event was fired