Question

I am using the jQueryFileTree at http://abeautifulsite.net/notebook/58 and I want to distinguish between the dblclick and click events as a click is always triggered by a dblclick.

Googling about led to be a technique in which click is handled by a timer which kicks in when a dblclick does not cancel it.

Is there some way this can be used with jQuery and the jQuery example in an elegant manner?

Was it helpful?

Solution

You can use setTimeout() and clearTimeout() to realize the timer functionality:

var timeout;
var delay = 500;  // Delay in milliseconds

$("...")
    .click(function() {
        timeout = setTimeout(function() {
            // This inner function is called after the delay
            // to handle the 'click-only' event.
            alert('Click');
            timeout = null;
        }, delay)
    }
    .dblclick(function() {
        if (timeout) {
            // Clear the timeout since this is a double-click and we don't want
            // the 'click-only' code to run.
            clearTimeout(timeout);
            timeout = null;
        }
        // Double-click handling code goes here.
        alert('Double-click');
    }
;

OTHER TIPS

jQuery Sparkle provides a clean elegant solution for this, by implementing a singleclick custom event. By doing this, you can use it just like any other event, so:

$('#el').singleclick(function(){});
// or event
$('#el').bind('singleclick', function(){});

It also provides custom events for the last and first clicks of a series of clicks. And the lastclick custom event actually passes the amount of clicks back! So you could do this!

$('#el').lastclick(function(event,clicks){
    if ( clicks === 3 ) alert('Tripple Click!');
});

You can find the appropriate demo showcasing what I've just said right here and the source code for defining the custom event right here. It's open source under the AGPL licence, so you can feel free to grab what you need out of it worry free! :-) It's also actively developed on a day to day basis so you will never be short on support.

But most importantly it is a DRY Plugin/Effect Framework to allow you to develop plugins and extensions much more easily. So I hope this helps to achieve that goal!

Look at the following code

$("#clickMe").click(function (e) {
    var $this = $(this);
    if ($this.hasClass('clicked')){
        alert("Double click");
        //here is your code for double click
        return;
    }else{
         $this.addClass('clicked');
        //your code for single click
         setTimeout(function() { 
                 $this.removeClass('clicked'); },500);
    }//end of else
});

Demo goes here http://jsfiddle.net/cB484/

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