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?
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:
100ms
to account for potential timestamp approximations. It's possible for the event timestamps to vary by as little as 1ms
..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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With