Emmanuel Akinfulubi

JavaScriptEvents

Handle a double click event in JavaScript

Beginner · 4 min read

Double-clicking is how you open a file on a desktop, select a word in a document, or start renaming something in a list. Browsers have an event for it, so listening for a double click takes one line. The surprise is what else fires on the way there.

In this tutorial you will listen for a double click on a button, find out which events a double click really sends, and then make a single click and a double click do different things without stepping on each other. You should have used addEventListener and seen setTimeout before.

The dblclick event

The event's name is dblclick: all lowercase, no hyphen, and "double" shortened to "dbl". If you write doubleclick or dblClick, no error appears. Your listener just never runs, because no event has that name.

The page has one button:

index.html

<button id="target" type="button">Click me</button>

setTimeout and clearTimeout, briefly

setTimeout(fn, ms) runs fn once, after ms milliseconds. It returns an id number. clearTimeout(id) cancels it, as long as it hasn't run yet. We will need both in Step 4.

Here is the exercise. Try it yourself first, or read on and we will build it together.

10 Act on a double click

easy

Listen for a double click. Then work out what else fires on the way there, and why that is a problem.

Stuck? Three hints, smallest first
  1. 1. The event is dblclick, spelled without a hyphen or a capital.
  2. 2. A double click also fires click twice, first.
  3. 3. So if both are handled, the single-click action runs before the double-click one.

Step 1: listen for a double click

Step 1

const target = document.getElementById('target');
const log = [];
target.addEventListener('dblclick', () => log.push('dblclick'));
target.dispatchEvent(new Event('dblclick'));
console.log(log); // ['dblclick']

That's the whole basic exercise. Now the interesting part.

Step 2: what a real double click sends

A double click is not a separate gesture that replaces the clicks. The browser fires click, then click again, and only then dblclick. Listen for both, and fake that sequence:

Step 2

const target = document.getElementById('target');
const log = [];
target.addEventListener('click', () => log.push('click'));
target.addEventListener('dblclick', () => log.push('dblclick'));
target.dispatchEvent(new Event('click'));
target.dispatchEvent(new Event('click'));
target.dispatchEvent(new Event('dblclick'));
console.log(log); // ['click', 'click', 'dblclick']

The click listener ran twice before the dblclick listener got its turn.

Step 3: why that's a problem

Imagine a list where one click opens an item and a double click renames it. A user double-clicks to rename. First the item opens, then it opens again, and only then does renaming start. That is the classic symptom of handling both events on one element.

If the single-click action is something harmless, like highlighting the item, running it twice doesn't matter. If it's visible or slow, you need to tell the two apart.

Step 4: wait to see if a second click is coming

The fix is to delay the single-click action a little, and cancel it if a double click arrives in the meantime.

Step 4

const target = document.getElementById('target');
const actions = [];
let pending = null;
target.addEventListener('click', () => {
  clearTimeout(pending);
  pending = setTimeout(() => actions.push('single'), 250);
});
target.addEventListener('dblclick', () => {
  clearTimeout(pending);
  actions.push('double');
});
// a double click: click, click, dblclick
target.dispatchEvent(new Event('click'));
target.dispatchEvent(new Event('click'));
target.dispatchEvent(new Event('dblclick'));
setTimeout(() => console.log(actions), 300); // ['double']

Here's what happens. The first click plans a "single" for 250 milliseconds later. The second click cancels that plan and makes a new one. Then dblclick cancels the new plan too and records "double". When we look after 300 milliseconds, only "double" is there.

A lone click works as you'd hope:

JavaScript

target.dispatchEvent(new Event('click'));
setTimeout(() => console.log(actions), 300); // ['double', 'single']

Nothing cancels the plan this time, so 250 milliseconds later "single" is recorded.

The full solution does the same thing with a pretend clock instead of real timers, so its checks don't have to wait.

The cost of waiting

The delay isn't free. Every single click now takes a quarter of a second to do anything, which can make an interface feel sluggish. That's why most interfaces avoid giving one element both a single-click and a double-click action. If you can, choose one, or move the second action onto a separate button.

The full solution

The panel logs the events from one click and from a double click, then runs the delayed version. Its checks confirm a single click fires click once, a double click fires three events with click twice first and dblclick last, and the delayed version reports one single and one double with no false single before the double. Press Run, then click and double-click the live demo to see the order for yourself.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const target = el('button', { id: 'target', type: 'button' }, 'Click me');
document.body.appendChild(target);

const log = [];
let renames = 0;

target.addEventListener('click', () => log.push('click'));
target.addEventListener('dblclick', () => { log.push('dblclick'); renames++; });

// A real double click sends click, click, dblclick — in that order.
const doubleClick = () => {
  fire(target, 'click');
  fire(target, 'click');
  fire(target, 'dblclick');
};

fire(target, 'click');
console.log('one click :', log);

log.length = 0;
doubleClick();
console.log('double    :', log, '<- click fired twice BEFORE dblclick');

// If a single click does something visible, this is the fix: wait long enough to
// know a second click is not coming.
const clocked = [];
let pending = null;
const smart = {
  click() {
    clearTimeoutStub(pending);
    pending = setTimeoutStub(() => clocked.push('single'), 250);
  },
  dblclick() {
    clearTimeoutStub(pending);            // cancel the pending single
    clocked.push('double');
  },
};
// A tiny injected clock, so the wait costs nothing.
let now = 0;
let jobs = [];
let nextId = 1;
function setTimeoutStub(fn, ms) { const id = nextId++; jobs.push({ id, fn, at: now + ms }); return id; }
function clearTimeoutStub(id) { jobs = jobs.filter((j) => j.id !== id); }
function advance(ms) {
  now += ms;
  const due = jobs.filter((j) => j.at <= now);
  jobs = jobs.filter((j) => j.at > now);
  for (const j of due) j.fn();
}

smart.click(); advance(300);
smart.click(); smart.click(); smart.dblclick(); advance(300);
console.log('with a delay:', clocked, '<- one single, one double, no false single');

Output


      
12 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 12 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

12 checks

test('a single click fires click once', (() => { log.length = 0; fire(target, 'click'); return log; })(), ['click']);
test('a double click fires three events', (() => { log.length = 0; doubleClick(); return log.length; })(), 3);
test('and click comes first, twice', log.slice(0, 2), ['click', 'click']);
test('with dblclick last', log.at(-1), 'dblclick');
test('so a click handler runs during a double click', log.filter((l) => l === 'click').length, 2);
test('the dblclick handler ran once', renames, 2);
test('the event name has no capital or hyphen', 'dblclick', 'dblclick');
test('the delayed version reports one single click', clocked.filter((c) => c === 'single').length, 1);
test('and one double', clocked.filter((c) => c === 'double').length, 1);
test('with no false single before the double', clocked, ['single', 'double']);
test('cancelling the pending single is what does it', jobs.length, 0);
test('a dblclick alone still works', (() => { log.length = 0; fire(target, 'dblclick'); return log; })(), ['dblclick']);

A double click is not a separate gesture the browser tells you about instead of clicks — it fires click, click, then dblclick, and the assertions pin down that order. So if a single click does anything visible, a double click does it twice before the double-click handler gets a turn. The classic symptom is a list where double-clicking to rename also opens the item twice.

The fix is to delay the single-click action by roughly 250ms and cancel it if dblclick arrives. That is shown above with an injected clock so the wait costs no real time. It is worth saying that the delay is a real cost: every single click now feels slightly slow, which is why most interfaces avoid giving the same element both behaviours.

Common mistakes

  • Misspelling the event. doubleclick and dblClick never fire, and there's no error. It's dblclick.
  • Forgetting that a double click also clicks. The click handler runs twice before dblclick. Plan for it.
  • Not cancelling the pending single click. Without clearTimeout in the dblclick handler, a double click also triggers the single-click action afterwards.

Try it yourself

  1. Show the log on the page in a pre element, one event per line.
  2. Change the delay from 250 to 600 milliseconds. Click once and notice how long the page takes to respond.
  3. Make a list item that turns bold on a single click and asks for a new name with prompt() on a double click.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.