Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

javascript - Listen to double click not click

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); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...