Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double click event on 2 different items still triggers

Tags:

jquery

I am trying to make an item from 1 list move to a second list when it is double clicked. Then when you single click it, move it back to the first list.

The problem I encountered with this is that when rapidly clicking items in the second list, double click events will trigger, despite not clicking on the same item.

You can witness the problem in this jsfiddle

https://jsfiddle.net/9afn4s7q/

$('.item').dblclick(function () {
  $(this).detach();
  $('#list2').append($(this));
  $(this).click(function () {
    $(this).detach();
    $('#list1').append($(this));
  });
});

How do I stop a double click event from triggering when clicking different items?

like image 251
JREN Avatar asked Nov 09 '22 21:11

JREN


1 Answers

You're seeing this behavior because the dbclick event is still being fired after the element is appended.

In other words, when clicking on an item in the second list, the second click event is being fired at approximately the same time as the dbclick event. To work around this, you could compare the event timestamps in order to determine if the second click event fired a dbclick event after it was appended.

In the example below, the lastClickTimeStamp variable is updated each time the click event is fired. In order to prevent the weird behavior that you are seeing, a check is made to determine whether the last click was fired before the dbclick event is fired.

Updated Example

var lastClickTimeStamp = 0;
$('#list1').on('dblclick', '.item', function(event) {
  if (event.timeStamp > lastClickTimeStamp) {
    $('#list2').append(this);
  }
});
$('#list2').on('click', '.item', function(event) {
  lastClickTimeStamp = event.timeStamp + 100;
  $('#list1').append(this);
});

Side notes:

  • I added 100ms to account for potential timestamp approximations. It's possible for the event timestamps to vary by as little as 1ms.
  • I used event delegation in order to avoid the nested event listeners (although you were already aware of that).
  • Since you're using jQuery version 1.6.4, you would use the .delegate() method instead of the .on() method.

As I pointed out in the comments, you could alternatively append the element to the first list with a delay. In doing so, the delegated dbclick event isn't fired.

Updated Example

$('#list1').on('dblclick', '.item', function(event) {
  $('#list2').append(this);
});
$('#list2').on('click', '.item', function(event) {
  setTimeout(function () {
    $('#list1').append(this);
  }.bind(this), 5);
});

I feel like both of these solutions are relatively hackish, but nonetheless, they seem to work.

like image 123
Josh Crozier Avatar answered Dec 13 '22 01:12

Josh Crozier