←back to thread

294 points ulrischa | 1 comments | | HN request time: 0.2s | source
Show context
G1N ◴[] No.42174685[source]
RE this line of code at the bottom of the article:

  const isInvokedByMouse = event =>
  event.type === 'click' && (event.screenX !== 0 || event.screenY !== 0);
Why do you even have to check if screenX and screenY are non-zero (as opposed to just checking typeof event.screenX == "number")? Wouldn't that mean (and this is a wild edge-case) that if someone positioned their browser window so that the menu was in the top left corner (at position 0,0) the event handler would break again? Is this to block synthetic click events like (<div />).click()? Keyboard events don't have a screenX or screenY from what I remember as well.
replies(3): >>42175051 #>>42179466 #>>42180262 #
chrismorgan ◴[] No.42180262[source]
> Keyboard events don't have a screenX or screenY from what I remember as well.

Remember that this is on 'click' events. The 'click' event type is a bit of a misnomer: it’s arguably more “activate” than “click”, because (depending a little on platform conventions) it also triggers on Space/Enter if the element is focused. But importantly it’s still a 'click' event: so it’s still a PointerEvent, not a KeyboardEvent. Since various of the fields aren’t appropriate, they get zeroed. So, screenX == 0 && screenY == 0 means either that the pointer is at the top left of the screen, or that the event was not generated by a pointer (that is, by a keyboard).

Try it out yourself, if you like, by loading a URL like this and activating by keyboard and by mouse and comparing the events.

  data:text/html,<button onclick=console.log(event)>
In reality, if you used such a check more generally, you’d find it wasn’t such a rare edge case: if the page is fullscreen, corner clicking is actually pretty common, and if you have buttons that are supposed to be in the corner, they should certainly activate on exact-corner clicks. (See also Fitt’s law <https://en.wikipedia.org/wiki/Fitts's_law#Implications_for_U...>.)

Fortunately, there’s a proper fix: `event.pointerId === -1` indicates non-pointer (viz. keyboard) activation.

replies(1): >>42200997 #
1. G1N ◴[] No.42200997[source]
Very informative, thank you!