jQuery: How Do I simulate Drag and Drop in Code?

Timothy Khouri picture Timothy Khouri · Jul 22, 2009 · Viewed 29.4k times · Source

EDIT: Here's a link to show you my sample code: http://www.singingeels.com/jqtest/

I have a very simple page that references jquery-1.3.2.js, ui.core.js (latest version) and ui.draggable.js (also latest version).

I have a div that I can drag around very easily (using the mouse of course):

<div id="myDiv">hello</div>

and then in JavaScript:

$("#myDiv").draggable();

This is works perfectly. But, I need to be able to simulate a 'drag and drop' using code alone. I have it mostly working, but the problem is that the events that are firing are the placeholder events.

If you open "ui.core.js" and scroll to the bottom... you'll see this:

// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(event) { },
_mouseDrag: function(event) { },
_mouseStop: function(event) { },
_mouseCapture: function(event) { return true; }

Why aren't the events being extended properly in my simulation, but when you click down with the mouse, they are? - Any ideas on how to force the _mouseDrag: property to obey the overriding extension in "ui.draggable.js"?

Solving this would be huge - and I plan to show the major benefits later.

Thanks, -Timothy

EDIT: Here's a link to show you my sample code: http://www.singingeels.com/jqtest/

EDIT 2: Click that link above and view-source... you'll see what I'm trying to do. Here's a snippet:

$(document).ready(function() {
    var myDiv = $("#myDiv");

    myDiv.draggable();

    // This will set enough properties to simulate valid mouse options.
    $.ui.mouse.options = $.ui.mouse.defaults;

    var divOffset = myDiv.offset();

    // This will simulate clicking down on the div - works mostly.
    $.ui.mouse._mouseDown({
        target: myDiv,
        pageX: divOffset.left,
        pageY: divOffset.top,
        which: 1,

        preventDefault: function() { }
    });
});

Answer

StuperUser picture StuperUser · Jan 5, 2011

There's a question in the JQuery forum about it. It's not resolved at the time of writing, but may have more information in the future.


EDIT: It was answered on the forum:

I recommend you use the simulate plugin which is what jQuery UI uses for unit testing drag and drop:

https://github.com/jquery/jquery-ui/blob/master/external/jquery-simulate/jquery.simulate.js

You can see examples of use by looking at the unit tests

https://github.com/jquery/jquery-ui/blob/master/tests/unit/draggable/core.js

https://github.com/jquery/jquery-ui/blob/master/tests/unit/draggable/events.js

Thanks to rdworth for that.