Question

I am trying to set some text in window for single and double click in jquery.

But I am facing the ambiguity for double click.

When trying to do double click , first single click function works and then double click works.

Similar question is here check here and it was very old. Also it has some problem.

Any new answer using the latest jquery version.

Check the live demo here of my problem live demo

This my code ,

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

<a id="press" href="http://jquery.com">Click here</a>
<div id="log"></div>

<script>

$("#press").click(function(event) {
  event.preventDefault();
  $("#log").text("I am single click !");
return false;
});

$("#press").dblclick(function(event) {
      event.preventDefault();
      $('#log').text("I am double  click !");
      return false;
    });
</script>

</body>
</html>

Hope our stack users will help me.

Was it helpful?

Solution 2

I got the closest solution by ,

<a id="press" href="javascript:void(0)" onclick="singleClick(event)"
    ondblclick="doubleClick(event)">Click here</a>

<div id="log"></div>

My JavaScript will be ,

var timer;
var status = 1;

function singleClick(event) {

    event.preventDefault();
    status = 1;
    timer = setTimeout(function() {
        if (status == 1) {
            alert("I am single click !");
            document.getElementById("log").innerHTML ='I  am single click !';
        }
    }, 500);

}

function doubleClick(event) {

    event.preventDefault();
    clearTimeout(timer);
    status = 0;
    alert("I am double click !");
    document.getElementById("log").innerHTML = 'I  am a double  click!';
}

OTHER TIPS

The way around the problem is to use a timeout for the click event to give the user time to doubleclick.
If the user clicks twice within a certain timeframe, it's a doubleclick, if the user only clicks once, it's a normal click:

$('#press').click(function (event) {
    event.preventDefault();

    if ( $(this).data('dblclicked') ) {
        $('#log').text('No google today!');
        clearTimeout( $(this).data('clicked') );
        $(this).data('dblclicked', false);
    }else{
        var self = this;
        $(this).data('dblclicked', true).data('clicked', setTimeout(function() {
            $('#log').text('google !');
            $(self).data('dblclicked', false);
        },300));
    }
});

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top