Skip to content
Advertisement

Is there any way to make double-click events work in phones with vanilla JavaScript?

I realized my double click events don’t work when I toggle the device toolbar. I googled but I’ve seen only jQuery stuff and I have no idea about jQuery. How do I make this work?

stuff.addEventListener('dblclick', openOtherStuff)

I am trying to open a modal with this event. it perfectly works on pc, doesn’t work on mobile.

Advertisement

Answer

unfortunately you can’t listen for double tap event but you can measure the time difference between two single taps using touchstart event.

let lastClick = 0;
const ele = document.querySelector('div');
ele.addEventListener('touchstart', function(e) {
  e.preventDefault(); // to disable browser default zoom on double tap
  let date = new Date();
  let time = date.getTime();
  const time_between_taps = 200; // 200ms
  if (time - lastClick < time_between_taps) {
    // do stuff
    console.log("done");
  }
  lastClick = time;
})
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
}

div {
  width: 100px;
  height: 100px;
  background: rebeccapurple;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div>Touch</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement