0

I'm trying to implement two different functionalities to an element, one after a single click and another one after two clicks. I'm using a setTimeout to detect when a single click is performed, but this way both functions end up being performed, because the setTimeout continues counting, so I had the idea of ​​stopping the time as soon as the second click is performed, but after that the setTimeout stops working and everything is seen as a double click, so I modeled everything until it looked like this

function howManyClicks(element){
    var time;
    let realization = new Promise((resolve)=>{
        time = setTimeout(()=>{
            resolve(1);
            element.removeEventListener('click', dobleClick);
        }, 200);
        element.addEventListener('click', dobleClick);
        function dobleClick(){
            element.removeEventListener('click', dobleClick);
            clearTimeout(time);
            resolve(2);
        }
    });
    realization.then((value)=>{
        return value;
    });
}

I think there are already enough non-functional and unnecessary things there, but they were my attempts to reach that goal. Does anyone know how to resolve?

Emanoel José
  • 125
  • 1
  • 6
  • 2
    You could use the `dblclick` event to detect double clicks! https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event – Kokodoko Jun 11 '23 at 20:09

2 Answers2

1

Other than the fact that there already exists a double click event which our friend above pointed out...

A double click will almost always trigger a single click prior to a double click firing, because most users out there can't perfectly synchronize the two buttons to prevent the left button from firing, so it's a bad idea and the reason next to nobody uses the dblclick event.

Therefore the best solution for dual mouse button functions with no conflicts, is to use the left and right mouse buttons...

 element.addEventListener('click',function_A);  // left click

 element.addEventListener('contextmenu',function_B);  // right click

Although I have no idea how the right or double clicks would work on a Macintosh having never used one! :)

  • Thanks to everyone who tried to help me. Well, I couldn't solve my specific problem with the suggestions, but I managed to find a method. I will provide an exemplary code for those who arrive here with identical problems and do not know how to solve it – Emanoel José Jun 11 '23 at 22:05
0

var clicks = 0;
function func(element){
  clicks++;
  let time = setTimeout(()=>{
    if(clicks == 1){
      element.innerHTML = 'One click';         
      clicks = 0;
    }
  },200);
  if(clicks == 2){
    element.innerHTML = 'Two clicks';  
    clearTimeout(time);
    clicks = 0;
  }
}
<button onclick="func(this)">Button</button>

Enjoy!!!

Emanoel José
  • 125
  • 1
  • 6