开发者

Different function for same class on 'click' / 'dblclick'

This are my two functions, on single click it works fine, but on dblclick both functions execute, any idea? I tried using live instead of delegate but still both functions execute on dblclick

// Change Status on click
$(".todoBox").delegate("li", "click", function() {
    var id = $(this).attr("id");
    $.ajax({            
        //ajax stuff
});

return false;
});



// Double Click to Delete
$(".todoBox").delegate("li", "dblclick", function(){
    var id = $(this).attr("id");
    $.ajax({  
     开发者_如何学编程 //ajax stuff 
    });

return false;
});


From the API documentation:

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 and others only one. If an interface that reacts differently to single- and double-clicks cannot be avoided, then the dblclick event should be simulated within the click handler. We can achieve this by saving a timestamp in the handler, and then comparing the current time to the saved timestamp on subsequent clicks. If the difference is small enough, we can treat the click as a double-click.

I think that means you'd do your click action in the timeout handler. If you get another click, and the timeout handler hasn't happened yet, you cancel the timeout and do the dblclick code.


As Pointy pointed out, click and dblclick on same element can be tricky, and here's an implementation how you can 'fake' it using setTimeout:

var clickTimeout = false;
$('#element').click(function() {

    if(clickTimeout !== false) {
        // I'm doubleclick!
        clearTimeout(clickTimeout);
        clickTimeout = false;
    } else {        
        clickTimeout = setTimeout(function() {
            // I'm click!
            clickTimeout = false;
        }, 400);
    }
});

Basically that means that if the user clicks again on the same element within 400 milliseconds, it's a doubleclick. Note that in this case the clickTimeout variable is global and will affect all elements so it might result in some strange behaviour if user clicks two different elements within 400 milliseconds, but this should give you some ideas at least.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜