I have an image inside a div. I want that image to be draggable within the div, and I want to store the coordinates of the image. Using a ‘stop’ event on the Draggable works well for this and does exactly what I want. I also want the same code to be run on the ‘create’ event. However, when using the same code in the ‘create’ event it seems that the ‘ui’ object that is passed in is empty:
$(document).ready(function() {
$('#imageitem').draggable({
containment: "parent",
stop: function(event, ui) {
console.log(ui); // results in full object being printed
},
create: function(event, ui) {
console.log(ui); // results in empty object being printed: Object { }
},
});
});
The docs for UI/Draggable show that the create callback should receive the ‘ui’ object:
$( ".selector" ).draggable({
create: function(event, ui) { ... }
});
I’m trying to access ui.offset, which is not available because of the empty object. If I understand this correctly, the ‘ui’ object should already exist in the DOM at this point, since I’m only attaching a draggable to it. Shouldn’t I be able to access ui.offset during the ‘create’ of the draggable event?
Admittedly, I’m new to jQuery so I could be missing something here.
It seems like you should probably be able to know the draggable item’s
offsetwhen it is created. Just inspect the element after the page loads. If you need to pass the values, couldn’t you just create defaults for them — or is the object going to be randomly positioned?Secondly, (skirting the fact that it would appear that the
uielement should have lots of information for you on create) you should be able to access the offset of any element on the page by finding that element and calling.offset()upon it. i.e., within your create statement, locate the draggable element by whatever selector you want to use and find out the offset that way:Edit: Here is a jsfiddle displaying how you could access the properties on create.