Andrew Mao
Andrew Mao

Reputation: 36900

How to interpret short drag events as clicks

Is there a concise way to have short-length, short-duration drag events be interpreted as click events? For example, I am using d3 and defining the following events that are supposed to capture a click, mouse move (no drag), and drag events on an SVG, as well as handling the end of such events:

@svg
  .on("click", @plot_click )
  .on("mousemove", @plot_mousemove )
  .on("mousedown.drag", @plot_drag )
  .on("touchstart.drag", @plot_drag )

# Global event detectors
d3.select("body")      
  .on("mouseup.drag", @mouseup)
  .on("touchend.drag", @mouseup)  

However, short click events where the mouse isn't perfectly still are registering as very small drag events, and this is very annoying for my interface. What's a good way to fix this?

While I'm defining events handlers using d3, I would be willing to adapt any general Javascript approach for this.

Upvotes: 2

Views: 334

Answers (1)

polm23
polm23

Reputation: 15593

  1. On mousedown, save the cursor position to a global variable (mousePosOnLastDown).
  2. On mouseup, check if the cursor has moved far enough.
    • If it has, execute the drag action.
    • If it has not, execute the click action.
    • Clear the mousedown cursor position.

Edit From OP: It made sense to not use the click action at all, and only mousedown/mouseup actions. I changed your answer accordingly.

Upvotes: 1

Related Questions