Mouse event

Explore the basics of handling mouse events in JavaScript

see moreJavaScript events

When viewing mouse events, we can interact with it

  • mousedownMouse button pressed
  • mouseupRelease the mouse button
  • clickClick event
  • dblclickDouble-click event
  • mousemoveWhen the mouse moves over the element
  • mouseoverWhen the mouse moves over an element or one of its child elements
  • mouseenterWhen the mouse is moved over the element. asmouseoverBut it will not bubbling (more on that later!)
  • mouseoutWhen the mouse moves out of the element, and when the mouse enters the child element
  • mouseleaveWhen the mouse moves out of the element. asmouseoutBut it will not bubbling (more on that later!)
  • contextmenuWhen opening the context menu, for example, when you click on the right mouse button

Events overlap. When you track aclickEvents, like trackingmousedownWith onemouseupevent. in the case ofdblclick,clickHe was also fired twice.

mousedown,mousemovewithmouseupCan be used in combination to track drag and drop events.

Be carefulmousemove, Because it will trigger multiple times during the mouse movement. We need to applyThrottling, This is more of what we will talk about when analyzing scrolling.

In an even number handler, we can access many attributes.

For example, when a mouse event occurs, we can checkbuttonThe properties 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 attributes we can use:

  • altKeyTrue if the alt key was pressed when the event was triggered
  • buttonIf so, the number of the button that was pressed when the mouse event was triggered (usually 0 = main button, 1 = middle button, 2 = right button). Act on events caused by clicking a button (for example, click)
  • buttonsIf any, a number indicating the button that was pressed on any mouse event.
  • clientX/clientYThe x and y coordinates of the mouse pointer relative to the browser window, independent of scrolling
  • ctrlKeyTrue if the ctrl key is pressed when the event is triggered
  • metaKeyReturns true if the meta key is pressed when the event is triggered
  • movementX/movementYThe x and y coordinates of the mouse pointer relative to the position of the last mousemove event. Used to track the mouse speed when moving the mouse
  • regionUse in Canvas API
  • relatedTargetThe secondary goal of the event, such as when moving
  • screenX/screenYThe x and y coordinates of the mouse pointer in screen coordinates
  • shiftKeyTrue if the Shift key was pressed when the event was triggered

Download mine for freeJavaScript beginner's manual


More browser tutorials: