JS DOM - 04.01 - Mouse Events

Mouse Event types

mousedown/mouseup Mouse button is clicked/released over an element.

mouseover/mouseout Mouse pointer comes over/out from an element.

mousemove Every mouse move over an element triggers that event.

click Triggers after mousedown and then mouseup over the same element if the left mouse button was used.

dblclick Triggers after two clicks on the same element within a short time-frame. Rarely used nowadays.

contextmenu Triggers when the right mouse button is pressed.

Event order

A left-button click first triggers mousedown, then mouseup and click when it’s released.

In cases when a single action initiates multiple events, their order is fixed. That is, the handlers are called in the order mousedown → mouseup → click.

Mouse button

Click-related events always have the button property, which allows to get the exact mouse button. mousedown and mouseup handlers may need event.button, because these events trigger on any button, so button allows to distinguish between “right-mousedown” and “left-mousedown”.

Modifiers: shift, alt, ctrl and meta

All mouse events include the information about pressed modifier keys. They are true if the corresponding key was pressed during the event.

Event properties:

  • shiftKey: Shift
  • altKey: Alt (or Opt for Mac)
  • ctrlKey: Ctrl
  • metaKey: Cmd for Mac
<button id='button'>press Alt+Shift+Click to work</button>

<script>
	button.onclick = function(event) {
		if(event.altKey && event.shiftKey) {
			alert( 'Hooray!' )
			}
		};
</script>

Coordinates: clientX/Y, pageX/Y

All mouse events provide coordinates in two flavours:

  1. Window-relative: clientX and clientY.
  2. Document-relative: pageX and pageY.

pageX/Y document-relative coordinates are counted from the left-upper corner of the document, and do not change when the page is scrolled.

while clientX/Y are counted from the current window left-upper corner. When the page is scrolled, they change.

For instance, if we have a window of the size 500x500, and the mouse is in the left-upper corner, then clientX and clientY are 0, no matter how the page is scrolled.

And if the mouse is in the center, then clientX and clientY are 250, no matter what place in the document it is. They are similar to position:fixed in that aspect.

Preventing selection on mousedown

The default browser action of mousedown is text selection, if it’s not good for the interface, then it should be prevented.