Charles
Charles

Reputation: 11796

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?

Upvotes: 4

Views: 5840

Answers (4)

Blaise
Blaise

Reputation: 13489

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();

Upvotes: 3

ashanbrown
ashanbrown

Reputation: 747

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;
  }
})

Upvotes: 3

A. Wolff
A. Wolff

Reputation: 74420

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::');
    }
});

Upvotes: 11

Charles
Charles

Reputation: 11796

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

Upvotes: 1

Related Questions