I create a new jQuery element after the mouse is in a down position and before it is released. (After mousedown).
I would like to programmatically trigger dragging
on the new element using jQuery UI, so that it will automatically begin dragging with my mouse movement. I don't want to have to release and then click the mouse again.
I have tried the following...
var element = $("<div />");
element.appendTo("body").draggable().trigger("mousedown");
...however this does not work.
Does anyone have any suggestions on how to accomplish this?
UPDATE: After some searching the poster of this question has the identical problem. However the suggested solution, which boils down to...
$("body").on("mousedown", function(e) {
$("<div />").draggable().appendTo("body").trigger(e);
});
...no longer works in the latest versions jQuery and jQuery-UI, and instead generates a Maximum Call Stack Exceeded error.
This is totally a hack, but it seems to do the trick:
Here's the plunker
My example uses an element that already exists instead of creating one, but it should work similarly.
You have to bind the mousedown event to the element in question, then you can trigger the event.
From http://api.jquery.com/trigger/
Hacks are not needed if you are creating the element during the event and that element is not too complicated. You can simply set draggable to the element that mousedown occurs and use draggable helper property to create a helper that is going to be your new element. On dragStop clone the helper to the location in dom you want.
Of course you would need to set position for the helper, so mouse is on it. This is just a very basic example.
The draggable plugin expects its mousedown events to use its namespace and to point to the draggable object as the target. Modifying these fields in the event works with jQuery 1.8.3 and jQuery UI 1.9.2.
Demo here: http://jsfiddle.net/maCmB/1/
Create your draggable function on mouseover
As the draggable initialization has already be done, your first mouse click will be taken into account