Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to double click not click

Tags:

javascript

dom

I'm just wondering why click event happening when I dbclick an element?

I have this code:(JSBIN)

HTML

<p id="hello">Hello World</p>

JavaScript

document.getElementById('hello').addEventListener('click', function(e){
  e.preventDefault();
  this.style.background = 'red';
}, false);
document.getElementById('hello').addEventListener('dbclick', function(){
  this.style.background = 'yellow';
}, false);

It should do different things for click and double click, but it seems when you double click on the p it catch click event in advance and ignore double click.

I tried preventDefault the click event too. How can I listen to just dbclick?

UPDATE

I had a typo in my code. dbclick is wrong. It's dblclick. Anyway the problem still exist. When user double clicks the click event happens.

This is updated code that prove it:(JSBin)

document.getElementById('hello').addEventListener('click', function(e){
  e.preventDefault();
  this.style.background = 'red';
  this.innerText = "Hello World clicked";
}, false);
document.getElementById('hello').addEventListener('dblclick', function(){
  this.style.background = 'green';
}, false); 
like image 968
Mohsen Avatar asked Oct 26 '11 00:10

Mohsen


People also ask

How do I listen to double-click?

To detect double clicks with JavaScript you can use the event listener dblclick . The dblclick event is supported in all modern browsers for desktop/laptops, even Internet Explorer 11. Unfortunately, it's not supported on all mobile devices, yet.

How can you tell the difference between single click and double-click?

Typically, a single click initiates a user interface action and a double-click extends the action. For example, one click usually selects an item, and a double-click edits the selected item.

How do I disable double-click event?

If you want to disable any mouse click action use addEventListener(event, function, useCapture) . Onclick ,call this function.


1 Answers

dblclick is not magical: though the second rapid click fires the dblclick event, the first click has already triggered its own event handler.

You should pretty much never set both a click and a dblclick event on a DOM element; when you do, you'll need fancy tricks with timers to mitigate the issue.

In this specific scenario, you'll also need to fix your typo (s/dbclick/dblclick/) to get the event to fire at all.

Also note that dblclick is not actually part of the DOM specification at all (not present in DOM Level 2 1.6.2). For this reason it's known as a "DOM Level 0" feature.

like image 92
Lightness Races in Orbit Avatar answered Oct 05 '22 21:10

Lightness Races in Orbit