Reputation: 19954
Is there a way to separate a click events functionality from a drag events functionality if they are both attached to the same object?
I am adding a class on click. My goal for my application is that when a user has 'clicked' and item, that it's draggable functionality is disabled.
Conversely, if a user drags an item, the click should not fire off.
Is this possible?
Here's my fiddle with the code below included...
html:
<div class="buttonBox"></div>
jQuery:
var bool = false;
var buttonBox = $(".buttonBox");
buttonBox.off("click");
buttonBox.on("click", function (event, ui) {
console.log("class Added");
$bool = true;
var self = $(this);
self.addClass("selectedBox");
});
buttonBox.draggable({
distance: 40,
disabled: bool,
revert: "invalid",
revertDuration: 400,
refreshPositions: true,
});
Upvotes: 0
Views: 106
Reputation: 3739
You can wait for a short while at the start of click event, and fire the click event function only if that element is not being dragged by then.
buttonBox.on("click", function (event, ui) {
setTimeout(function (ev, ui) {
if($(ev.target).hasClass("ui-draggable-dragging"))
return;
console.log("class Added");
$(ev.target).addClass("selectedBox");
}, 50, event, ui);
});
Fiddle: http://jsfiddle.net/doqpbuvy/3/
Upvotes: 1
Reputation: 74420
You could use the start
event of draggable element to set your logic:
buttonBox.on("click", function (event, ui) {
if($(this).hasClass('dragging')) {
$(this).removeClass('dragging');
return;
}
console.log("class Added");
$bool = true;
var self = $(this);
self.addClass("selectedBox");
});
buttonBox.draggable({
start: function(){
if($(this).hasClass('selectedBox')) return false;
$(this).addClass('dragging');
},
distance: 40,
disabled: bool,
revert: "invalid",
revertDuration: 400,
refreshPositions: true,
});
Upvotes: 1