2

I want to bind click and dblclick event on same DOM, but dblclick always active click event. How to do that two events don't influence each other!

MANOJ GOPI
  • 1,261
  • 10
  • 29
  • 1
    possible duplicate of [how to differentiate single click event and double click event?](http://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event) – Lorenzo Marcon Feb 03 '15 at 08:29

3 Answers3

1

Wait to respond to the click by a tiny amount via setTimeout, and don't do the click action if you see the double-click. Unfortunately, the timing is pretty tricky — too little and you get the click when you shouldn't, too much and clicks really lag.

var div = document.getElementById("the-div");
var clickTimer;
div.addEventListener("click", function() {
  clearTimeout(clickTimer);
  clickTimer = setTimeout(function() {
    snippet.log("clicked");
    clickTimer = 0;
  }, 250);
}, false);
div.addEventListener("dblclick", function() {
  clearTimeout(clickTimer);
  snippet.log("double-clicked");
}, false);
<div id="the-div">Click and/or double-click me</div><!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
0

Here's a demo using setTimeout that you can handle your click and dblclick events separately. Using a bool variable you can decide if it's a single click or double click and create handler accordingly.

HTML :

<div>Bingo</div>

CSS :

div{
    width : 100px;
    height : 100px;
    background-color: blue;
}

javaScript :

var div = document.getElementsByTagName("div")[0];
var isSingleClick = true;
div.onclick = function(){
    setTimeout(function(){
        if(isSingleClick){
            console.log("Click");
        }
    }, 500);
};

div.ondblclick = function(){
    console.log("DBLClick");
    isSingleClick = false;
    setTimeout(function(){
        isSingleClick = true;
    }, 500);
};

jsFiddle

Md Ashaduzzaman
  • 3,934
  • 2
  • 17
  • 33
0

if you use jquery, you can extend the jquery plugin. Using the javascript's non-blocking feature, and callback feature to handle this question. You can try this plugin: https://github.com/sgyyz/jquery-oneordoubleclick which apply for your jquery module.

$target_node.oneordoubleclick({oneclick: function(){
    console.log('you have click this node.');
   }, dbclick: function() {
    console.log('you have double click this node.');
   }
});
Troy Young
  • 159
  • 1
  • 11