Hanna
Hanna

Reputation: 10771

JQuery UI Draggable containment on start

I have a draggable that needs its containment set on start rather than on initialization.

edit The reason is that the draggable is part of a component and the component can exist in multiple places, so I need to check (on start) where in the DOM it exists and set the appropriate containment based on it's location.

For instance if draggable exists in element A, set containment to element A. If instance exists in element B, set it to element B.

To further clarify, I'm not looking for the immediate parent to be the container (as I believe this could be handled by passing "parent" to the control), but rather an arbitrary parent, hence me needing to do this logic on the start drag.

I've tried the obvious (jsfiddle)

$('#dragMe').draggable({
    start: function (event, ui) {
        $(this).draggable('option', "containment", '#container');
    },
});

This works, but only after you've dragged the element twice. So, for example, if you pick up the red box and drag it outside of the containment, it will let you. But if you drop it in the container and then drag it again, it will be properly contained. (Note, I'm using Chrome)

This leads me to believe that containment is checked before the start function is called.

Is there any way I can get JQuery UI to recognize the changed option or do I need to manually constrain the draggable within the bounds?

Upvotes: 0

Views: 814

Answers (1)

Hanna
Hanna

Reputation: 10771

I decided to follow up my suspicions that containment was being set before the start event was called.

I found this code in the JQuery UI source code:

//Set a containment if given in the options
this._setContainment();

//Trigger event + callbacks
if(this._trigger("start", event) === false) {
    this._clear();
    return false;
}

I simply switched the order around, so that the _setContainment() function would be called after the event. This fixed the issue for me, but I am a little concerned about the repercussions (including bugs/maintainability) this could have.

So if anyone has any better ideas I'd appreciate it.

Upvotes: 1

Related Questions