Skip to content
back

Mouse observer

The mouse observer is used to observe mouse movement relative to DOM Elements.

Usage

let element
const onMouseMove = () => {
  const mouse = element?.luge?.mouse
  if (!mouse || mouse.progressX === undefined) return
  console.log(mouse.x, mouse.y) // Pixel distances from the element's top-left
  console.log(mouse.progressX, mouse.progressY) // Clamped to 0–1
}

// Register these callbacks once, before luge.init().
luge.lifecycle.add('pageInit', done => {
  element = document.querySelector('#my-element')
  if (element) {
    luge.mouseobserver.add(element)
    luge.emitter.on('mouseMove', onMouseMove)
  }
  done()
}, 30)
luge.lifecycle.add('pageKill', done => {
  luge.emitter.off('mouseMove', onMouseMove)
  if (element) luge.mouseobserver.remove(element)
  element = null
  done()
})

Properties

Observed elements get new properties:

  • luge.mouse.x / luge.mouse.y: a number containing the mouse position relative to the element top left corner in px.
  • luge.mouse.progressX / luge.mouse.progressY: a number containing the mouse progress within the element bounding box (from 0 to 1).

Methods

add(element)

Add an element to the observer.

ParameterTypeDescription
elementHTMLElementDOM element to observe.

remove(element)

Remove an element from the observer.

ParameterTypeDescription
elementHTMLElementDOM element to remove.

Initialization

Use this service through a single initialized Luge instance. Register page-specific observations in pageInit after the core observers are ready (position 30), and remove your own callbacks when their owner is disposed. See Getting started.

Try it

Open the full demo