skip to Main Content

There are many questions and answers on the topic of separating ‘click’ and ‘dblclcik’ events on the same element. They usually use a timer, something like this:

let clicks = 0;
let clickTimer = -1;

function clickMe() {
   ++clicks;
  if (clicks === 1) {
      clickTimer = window.setTimeout(function() {
      count(false);  //perform single-click action 
      clicks = 0;    //after action performed, reset counter
    }, 200);
  }
  else {
      clearTimeout(clickTimer);    //prevent single-click action
      count(true);  //perform double-click action
      clicks = 0;   //after action performed, reset counter
  }
}

The trouble is the delay: 200 ms appears to be best from my trials, but then a slow dbl-click sometimes leads to two single clicks. Any bigger timeout leads to a very non-user-friendly delay before a normal click is processed.
Is there a better way?

A JSFiddle to play with, if required.

Using the dblclick event doesn’t work for me because it emits two click events first:

let click = document.getElementById("click");
let result = '';


function clickMe() {
  result += "single click ";
  showResult();
}

function doubleClick() {
  result += "double click ";
   showResult();
}

function showResult() {
 click.innerHTML = result;
 setTimeout(()=> {
    result = '';
  click.innerHTML = result;
 },1500)

}
<button onclick="clickMe()" ondblclick="doubleClick()">
  Click me
</button>

<p id="click"></p>

2

Answers


  1. Why not using native dblclick event (MDN dblclick event)?

    let click = document.getElementById("click");
    
    function clickMe() {
      click.innerHTML = "single click";
    }
    
    function doubleClick() {
      click.innerHTML = "double click";
    }
    <button onclick="clickMe()" ondblclick="doubleClick()">
      Click me
    </button>
    <p id="click"></p>
    Login or Signup to reply.
  2. Full support on most browsers since Dec. 22, 2023.
    Please enjoy the new eventListener dblclick.

    const card = document.querySelector("aside");
    
    card.addEventListener("dblclick", (e) => {
      card.classList.toggle("large");
    });
    aside {
      background: #fe9;
      border-radius: 1em;
      display: inline-block;
      padding: 1em;
      transform: scale(0.9);
      transform-origin: 0 0;
      transition: transform 0.6s;
      user-select: none;
    }
    
    .large {
      transform: scale(1.3);
    }
    <aside>
      <h3>My Card</h3>
      <p>Double click to resize this object.</p>
    </aside>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search