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:
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
}
I've tried various adjustments, and nothing has worked:
jQuery.Event
constructor and manually setting the above propertiesdocument.getElementById
mousedown
or mousedown.draggable
instead of drag
(this was based on some workaround code I found)
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With