Double-click an event on 2 different elements that are still triggering

I try to make an item from a list from one list to the second list when it is double-clicked. Then, clicking on it, return it to the first list.

The problem I encountered is that when you quickly click on items in the second list, double-click events fire despite the fact that they do not click on the same item.

You can see 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 to stop a double-click event on startup when clicking different elements?

+5
source share
1 answer

You see this behavior because the dbclick event is still dbclick after the item is added.

In other words, when you click on an item in the second list, the second-click event fires at about the same time as the dbclick event. To get around this, you could compare the timestamps of the event to determine if the second click event dbclick event after adding it.

In the example below, the lastClickTimeStamp variable lastClickTimeStamp updated each time the click event is click . To prevent the strange behavior that you see, it checks to see if the last click was fired before the dbclick event.

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 possible approximations of the timestamp. It is possible that event timestamps will only change by 1ms .
  • I used event delegation to avoid nested event listeners (although you already knew about it).
  • Since you are using jQuery version 1.6.4, you should use the .delegate() method instead of the .on() method.

As I noted in the comments, you can alternatively add an item to the first list with a delay. However, the delegated dbclick event dbclick not dbclick .

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 that both of these solutions are relatively hacky, but nonetheless they seem to work.

+1
source

Source: https://habr.com/ru/post/1240927/


All Articles