Pointer Events

Pointer events are a modern way to handle input from a variety of pointing devices, such as a mouse, a pen/stylus, a touchscreen, and more.

Pointer Event Types

Pointer events are named similarly to mouse events:

Pointer EventSimilar Mouse Event
pointerdownmousedown
pointerupmouseup
pointermovemousemove
pointerovermouseover
pointeroutmouseout
pointerentermouseenter
pointerleavemouseleave
pointercancel-
gotpointercapture-
lostpointercapture-

Pointer Event Properties

Pointer events have the same properties as mouse events, such as clientX, clientY, target, etc., with additional properties:

  • pointerId: Unique identifier of the pointer causing the event. Useful for handling multiple pointers (e.g., multi-touch).
  • pointerType: Type of pointing device, can be "mouse", "pen", or "touch".
  • isPrimary: true for the primary pointer (first finger in multi-touch).

Keydown and Keyup

The keydown event occurs when a key is pressed down, and keyup when it’s released.

document.addEventListener('keydown', function(event) {
  console.log('Key pressed:', event.key);
  if (event.key === 'Enter') {
    alert('Enter key pressed!');
  }
});

event.code and event.key

  • event.key: Returns the character of the key pressed.
  • event.code: Returns the physical key code.

Example:

Keyevent.keyevent.code
Zz (lowercase)KeyZ
Shift+ZZ (uppercase)KeyZ

Scrolling

The scroll event allows reacting to page or element scrolling. It can be useful for:

  • Showing/hiding additional controls or information based on scroll position.
  • Loading more data when the user scrolls to the end of the page.
window.addEventListener('scroll', function() {
  console.log('Scrolled to:', window.pageYOffset);
});

Prevent Scrolling

You can’t prevent scrolling directly using event.preventDefault() in a scroll event listener since it triggers after the scroll has already happened.

Instead, prevent the scroll-triggering event, like keydown for pageUp or pageDown. Alternatively, use CSS with the overflow property to control scroll behavior.