w3c / uievents

UI Events
https://w3c.github.io/uievents/
Other
145 stars 51 forks source link

Differentiate single click event and double click event #294

Open jimmywarting opened 3 years ago

jimmywarting commented 3 years ago

I found this solution to work the best okey among a few answer on SO

const button = document.getElementById('button')
let timer
button.addEventListener('click', event => {
  if (event.detail === 1) {
    timer = setTimeout(() => {
      console.log('click')
    }, 200)
  }
})
button.addEventListener('dblclick', event => {
  clearTimeout(timer)
  console.log('dblclick')
})

However it isn't perfect. it can still log both click and dbclick sometimes if you click somewhat slow & fast. The problem with all of the other solution i found where that they use a custom setTimeout delay.

Implementations MUST maintain the current click count when generating mouse events. This MUST be a non-negative integer indicating the number of consecutive clicks of a pointing device button within a specific time. The delay after which the count resets is specific to the environment configuration.

if you can't match the environment delay then you can't reliable differentiate single click event and double click event. I think a event is needed to know when UIevent.detail resets to 0 again.

I would want to have a single event that dispatch when consecutive clicks stops counting that tells you how many click you did.

button.addEventListener('consecutive-clicks-end', event => {
  console.log('you clicked on this button ' + event.detail + ' times')
  console.log('next click event will have a detail count of 1')
}, { once: true })

The only other solution is to build a own detail counter from scratch with your own debounce function