2

I'm writing event handlers using jQuery, and had a question about the click and double-click events. I've got an element with a class "file" on it. It has two event handlers attached to it, one for single-clicking on the element, the other for double-clicking. I wanted both to fire independently of the other, but it appears the click event always fires when the double-click event does.

$('.file').live('dblclick', function(//event handler code){});
$('.file').live('click', function(//event handler code){});

When a user double-clicks an item with an event attached to it, a double-click event should fire, which is normal. However, it appears any single-click events are firing as well. In jQuery, if a double-click event fires, does that mean a single-click event has always already fired on the same element?

palacsint
  • 28,416
  • 10
  • 82
  • 109
dsw88
  • 4,400
  • 8
  • 37
  • 50
  • Yes, and there's no way to change it nicely. Without a single click, how could there be a double click? – James Allardice Dec 21 '11 at 21:43
  • possible duplicate of [how to differentiate single click event and double click event?](http://stackoverflow.com/questions/5497073/how-to-differentiate-single-click-event-and-double-click-event) – Joseph Silber Dec 21 '11 at 21:54

3 Answers3

4

As James mentions in his comment, there cannot be one without the other. It's going to be a bit of a hack, but you can have these work independently with a timer:

$('.file').live('dblclick', function() {


  $(this).data('doubleClicked', true);
  //event handler code

});

function SingleClickHandle(this)
{
  if (! $(this).data('doubleClicked'))
  {
  //event handler code
  }
}

$('.file').live('click', function(){

  $(this).data('doubleClicked', false);
  setTimeout('SingleClickHandler(this)', 500); // is half a second enough to consider it a double-click?

});
Jake Feasel
  • 16,785
  • 5
  • 53
  • 66
0

This is the default behavior of jquery. You must use/do something like this: https://gist.github.com/399624

arocha
  • 29
  • 3
-3

Dont trust the first answers, thats really really bad. Use this instead:

$('.file').on('click', function()
{
    $(this).css('background', 'blue');
});

$('.file').on('dblclick', function(event){
    event.preventDefault();
    $(this).css('background', 'green');                               
});

http://jsfiddle.net/H42KV/

MrFischer
  • 117
  • 1
  • 4