Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically trigger a jQuery-UI draggable's "drag" event [duplicate]

I'm trying to trigger the drag event on a div immediately after wiring it up with jQuery-UI's draggable widget. I have some code that goes off when it gets dragged, and I'd like to also run this code once right after page load. I sometimes do this on other jQuery handlers using an idiom like this:

$('.foo').on('bar', function() {
   console.debug('bar!');
}).trigger('bar');

This doesn't seem to work with draggable. Here's my code:

var draggable = $('[draggable]').draggable({
   drag: function(event, ui) {
      //do some stuff
      console.debug(event);
   }
}).trigger('drag');

The drag handler gets called when I drag the item, but not on page load.

Info that might be relevant:

  1. When I drag the item, the event that shows up in the console looks like this:

    jQuery.Event {
       type: "drag",
       target: div#myElementId.ui-draggable,
       currentTarget: document,
       delegateTarget: document,
       data: null,
       //lots of other properties
    }
    
  2. I've tried various adjustments, and nothing has worked:

    • Using the jQuery.Event constructor and manually setting the above properties
    • Specifying the exact element I want with document.getElementById
    • Triggering mousedown or mousedown.draggable instead of drag (this was based on some workaround code I found)

  3. Yes, I realize I could just define the handler separately. Part of the reason I want to do this is to get access to the ui parameter, which gives me an easy way to get the element's position and offset. I could find them in other ways, but it's annoying. I'm also curious why this doesn't work.

  4. Searches on Google and SO have turned up no solutions, just workarounds that aren't relevant to me, along with other complaints about the same problem. Jörn Zaefferer from the jQUI team recommended the jQuery.simulate plugin as a workaround, so it may just not be possible. It seems odd that they wouldn't make it consistent with other jQuery events.

like image 690
Justin Morgan Avatar asked Jul 25 '14 17:07

Justin Morgan


Video Answer


1 Answers

Here is jquery ui plugin

https://github.com/jquery/jquery-ui/blob/9e8e339648901899827a58e5bf919f7dda03b88e/tests/jquery.simulate.js

include that on the page and then simply use

$("#myElement").simulate('drag');
like image 162
dav Avatar answered Sep 29 '22 11:09

dav