How to prevent 'click' event to fire before 'dblclick' event

2.9k Views Asked by At

I have to handle two events which are 'click' and 'dblclick' but the click event always fires before dblclick event and don't let dblclick event to execute. How can I make the event to execute correctly 'click' and 'dblclick'

google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng)
 });


 google.maps.event.addListener(map, 'click', function(event) {
   click_events(map, event.latLng)
 });
3

There are 3 best solutions below

3
On
var clicked = false;
google.maps.event.addListener(map, 'dblclick', function(event) {
   polygon(map, event.latLng);
   clicked = true;
 });


 google.maps.event.addListener(map, 'click', function(event) {
   if(clicked){
      click_events(map, event.latLng);
   }
 });
1
On

Use setTimeout and maintain the timeout object so that you can clear it on double click

var timeoutObj;
var timeoutThreshhold = ...; //number of milliseconds to wait for double click

google.maps.event.addListener(map, 'dblclick', function(event) {
   if (timeoutObj) {
     clear timeoutObj;
   }
   polygon(map, event.latLng);
 });


 google.maps.event.addListener(map, 'click', function(event) {
   timeoutObj = setTimeout(function() {
     timeoutObj = null;
     click_events(map, event.latLng);
   }, timeoutThreadhold);
 });
0
On

from https://api.jquery.com/dblclick/

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

how about handling it yourself, here an example for a multi-click detection:

let timeout, n = 0, delay = 250;

document.querySelector(".clicker").addEventListener("click", function(event) {
  ++n;
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    clickHandler.call(this, n, event);
    n = 0;
  }, delay);

  // a visual aid for how many times you've already clicked in this sequence
  event.target.textContent = n;
});

// just something visual
const cssNamedColors = ["Maroon","Red","Orange","Yellow","Olive","Green","Purple","Fuchsia","Lime","Teal","Aqua","Blue","Navy","Black","Gray","Silver","White"];
  
// decide what to do for *n* clicks:
function clickHandler(n, event) {
  event.target.style.background = cssNamedColors[n-1];
  event.target.textContent = n + " - " + cssNamedColors[n-1];
}
.clicker {
  display: block;
  background: #888;
  padding: 100px 0;
  text-align: center;
  font-size: 36px;
  color: white;
  cursor: pointer;
  text-shadow: -1px -1px 3px #000, 1px -1px 3px #000, -1px 1px 3px #000, 1px 1px 3px #000;
}
<div class="clicker">(Multi-)Click me</div>