How to programmatically invoke jQuery UI Draggable drag start?

Create your draggable function on mouseover

$('#futureDragableElement').mouseover(function() {
  $(this).draggable();
});

As the draggable initialization has already be done, your first mouse click will be taken into account


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.

$("body").on("mousedown", function(e) { 
  var div = $("<div />").draggable().appendTo("body");
  e.type = "mousedown.draggable";
  e.target = div[0];
  div.trigger(e);
});

Demo here: http://jsfiddle.net/maCmB/1/


UPDATE:

See fuzzyBSc's answer below. It's the proper way to do this.


This is totally a hack, but it seems to do the trick:

  var myDraggable = $('#mydraggable').draggable();
  
  // Yeah... we're going to hack the widget
  var widget = myDraggable.data('ui-draggable');
  var clickEvent = null;
  
  myDraggable.click(function(event){
      if(!clickEvent){
        widget._mouseStart(event);
        clickEvent = event;
      }
      else {
        widget._mouseUp(event);
        clickEvent = null;
      }
    });
  
  $(document).mousemove(function(event){
    console.log(event);
    if(clickEvent){
      // We need to set this to our own clickEvent, otherwise
      // it won't position correctly.
      widget._mouseDownEvent = clickEvent;
      widget._mouseMove(event);
    }
  });

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/

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user:

$('#foo').bind('click', function() {
      alert($(this).text());
    });
    $('#foo').trigger('click');