How to distinguish mouse "click" and "drag"

I think the difference is that there is a mousemove between mousedown and mouseup in a drag, but not in a click.

You can do something like this:

const element = document.createElement('div')
element.innerHTML = 'test'
document.body.appendChild(element)
let moved
let downListener = () => {
  moved = false
}
element.addEventListener('mousedown', downListener)
let moveListener = () => {
  moved = true
}
element.addEventListener('mousemove', moveListener)
let upListener = () => {
  if (moved) {
    console.log('moved')
  } else {
    console.log('not moved')
  }
}
element.addEventListener('mouseup', upListener)

// release memory
element.removeEventListener('mousedown', downListener)
element.removeEventListener('mousemove', moveListener)
element.removeEventListener('mouseup', upListener)

All these solutions either break on tiny mouse movements, or are overcomplicated.

Here is a simple adaptable solution using two event listeners. Delta is the distance in pixels that you must move horizontally or vertically between the up and down events for the code to classify it as a drag rather than a click. This is because sometimes you will move the mouse or your finger a few pixels before lifting it.

const delta = 6;
let startX;
let startY;

element.addEventListener('mousedown', function (event) {
  startX = event.pageX;
  startY = event.pageY;
});

element.addEventListener('mouseup', function (event) {
  const diffX = Math.abs(event.pageX - startX);
  const diffY = Math.abs(event.pageY - startY);

  if (diffX < delta && diffY < delta) {
    // Click!
  }
});