Skip to content Skip to sidebar Skip to footer

JQuery UI : Before Start Draggable

How to implement a before start event to have a change to change the position and place in the DOM of the draggable element before jQueryUI start to drag?

Solution 1:

You could extent prototype method:

SEE DEMO

var oldMouseStart = $.ui.draggable.prototype._mouseStart;
$.ui.draggable.prototype._mouseStart = function (event, overrideHandle, noActivation) {
    this._trigger("beforeStart", event, this._uiHash());
    oldMouseStart.apply(this, [event, overrideHandle, noActivation]);
};

$("#draggable").draggable({
    beforeStart: function () {
        console.log('beforeStart::');
    }
});

Solution 2:

I found that a method passed as the "helper" option to the sortable will get called before "start" and is passed (as the second argument) the item that has been clicked. You could do what you need to do in this method and then just return the element itself (the default "original" helper behavior). I'm using this to set the height of my container so that it doesn't collapse and trigger scrolling of the browser window. Here's what that looks like:

$(list).sortable({
  helper: function(event, element) {
    // it's too late if we wait until start to do this
    $(this).css('height', this.$().height());
    return element;
  }
})

Solution 3:

I didn't dare to access jQuery UI private variables, so I implemented it like this:

// The mouse interaction sequence for dragging starts with a mousedown action.
element.on('mousedown', function() {

    // Mouseup cancels dragging. This is a boring click.
    element.one('mouseup', function() {
        element.off('mousemove.mynamespace');
    });

    // Moving the mouse while holding mousedown is dragging.
    // This is also what sets off jQuery UI draggable, 
    // but we registered our event listeners first.
    element.one('mousemove.mynamespace', function() {

         // !! Your beforeStart code here.

    });
});

// Initialize jQuery UI draggable AFTER our own event listeners.
element.draggable();

Solution 4:

For that I used mouseup and mousedown:

var timeout;

$('.draggable').mousedown(function() {
  $('#dragContainer').append($(this));
  $(this).css({
    top: 0,
    left: 0
  });
});

$('.draggable').draggable(); 

I also used mouseup to reset the old parent and position if the mousedown was actually a click and not a drag.

It would be nice to have a beforeStart event which work with the distance option but I didn't find it...


Post a Comment for "JQuery UI : Before Start Draggable"