Detect click and double click on HTML

0

How can I do to detect if a simple click or double click on an HTML element <div> I have tried the following code:

<div onclick="alert('un click')" ondblclick="alert('doble click')"> Click aqui</div>

The problem is that it does not detect the double click, it always shows me the message "one click", as I do to detect one or the other.

    
asked by nullptr 29.11.2017 в 21:46
source

4 answers

1

It is not possible to use both events at the same time. You can do some kind of trick like the following:

var DELAY = 700,
    clicks = 0,
    timer = null;

$(document).ready(function() {

    $("a")
    .bind("click", function(e){

        clicks++;  //count clicks

        if(clicks === 1) {

            timer = setTimeout(function() {

                alert('Single Click'); //perform single-click action

                clicks = 0;  //after action performed, reset counter

            }, DELAY);

        } else {

            clearTimeout(timer);  //prevent single-click action

            alert('Double Click');  //perform double-click action

            clicks = 0;  //after action performed, reset counter
        }

    })
    .bind("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Click Me</a>

Although I do not understand why you want to do something like that.

    
answered by 29.11.2017 / 22:13
source
3

You do it the right way, ondblclick serves to perform a double click event on an element, however in the example that shows the result it will always be the alert ("a click ") , because when trying to double click, onclick detects the first interaction you do when clicking on the element.

    
answered by 29.11.2017 в 22:03
0

You can do it the way that every time you doubleclick on a certain element, you detect it with the addEventListener event. You can implement the same for the example click taken from w3schools .

 $(document).ready(function(){
        $("div").dblclick(function(){
            alert("Se ha hecho doble click sobre el Div.");
        });
    });
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
    </head>
    <body>

<div>Haz doble click.</div>

</body>
</html>
    
answered by 29.11.2017 в 22:11
0

Whenever you click or double click it will take the first click, you occupy doing something extra, such as measuring the time since you gave the first click if it takes for example 2 seconds and there is no other click to perform the action.

You can use the setTimeout

var dobleClick = false;
function onclick() {
  setTimeout(function () {
    if (dobleClick == false) {
      //Hacer algo
    }
    else {dobleClick = false;}
},500);
}
    
answered by 29.11.2017 в 22:20