0

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...

jsFiddle

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,

});
Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135

2 Answers2

1

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/

Ozan
  • 3,709
  • 2
  • 18
  • 23
  • this is a pretty nice solution as well. I'll look into both of these and see how they act in my project. Either way, I'll vote you up for taking the time to solve this. Thanks Ozan. – Dan Beaulieu Feb 05 '15 at 17:42
1

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,

});

-jsFiddle-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155