Javascript with jQuery: Click and double click on same element, different effect, one disables the other
The general idea:
Upon the first click, dont call the associated function (say single_click_function()). Rather, set a timer for a certain period of time(say x). If we do not get another click during that time span, go for the single_click_function(). If we do get one, call double_click_function()
Timer will be cleared once the second click is received. It will also be cleared once x milliseconds are lapsed.
BTW, check Paolo's reply out: Need to cancel click/mouseup events when double-click event detectedand of course the entire thread! :-)
Better answer: https://stackoverflow.com/a/7845282/260610
$('#alreadyclicked').val('no click');$('td.dblclickable').on('click',function(){ var $button=$(this); if ($button.data('alreadyclicked')){ $button.data('alreadyclicked', false); // reset $('#alreadyclicked').val('no click'); if ($button.data('alreadyclickedTimeout')){ clearTimeout($button.data('alreadyclickedTimeout')); // prevent this from happening } // do what needs to happen on double click. $('#action').val('Was double clicked'); }else{ $button.data('alreadyclicked', true); $('#alreadyclicked').val('clicked'); var alreadyclickedTimeout=setTimeout(function(){ $button.data('alreadyclicked', false); // reset when it happens $('#alreadyclicked').val('no click'); $('#action').val('Was single clicked'); // do what needs to happen on single click. // use $button instead of $(this) because $(this) is // no longer the element },300); // <-- dblclick tolerance here $button.data('alreadyclickedTimeout', alreadyclickedTimeout); // store this id to clear if necessary } return false;});
obviously use <td class="dblclickable">
I wrote a simple jQuery plugin that lets you use a custom 'singleclick' event to differentiate a single-click from a double-click. This allows you to build an interface where a single-click makes the input editable while a double-click expands it. Much like Windows/OSX filesystem rename/open UI.
https://github.com/omriyariv/jquery-singleclick
$('#someInput').on('singleclick', function(e) { // The event will be fired with a small delay but will not fire upon a double-click. makeEditable(e.target);}$('#container').on('dblclick', function(e) { // Expand the row...}