skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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!!!


  2. 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! 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search