I'm trying to get the x and y of the draggable object using JQuery.
The scenario is, I'm dragging and dropping an object onto another object and want to get the position of the drag&drop object. Edit: Now I can get the position of the object but I need more:
Here is what I've tried;
<script>
$(function() {
$('#draggable').draggable(
{
drag: function() {
var offset = $(this).offset();
var xPos = offset.left;
var yPos = offset.top;
$(this).text('x: ' + xPos + 'y: ' + yPos);
}
});
$("#droppable").droppable({
drop: function(event, ui) {
$(this)
.addClass("ui-state-highlight")
.find("p")
.html("Dropped!");
}
});
});
</script>
Now I can get the position of the draggable object but I need it to be resizable and in addition to getting x,y of the draggable, I also need the size of it.
Any help would be great!
Thanks.
You can use the
drag
event:JS Fiddle demo.
This demo brought to you by the
drag event
, and the methodsoffset()
andtext()
.Edited in response to comment from OP, to original question:
...uh, whoah...
I think this sort of covers the basics of what's asked for:
Updated JS Fiddle demo.
Newly-updated JS Fiddle demo, featuring
revert: invalid
, so dropping the draggable div anywhere but the droppable div will cause the draggable to animate back to its starting position. If that'd be appreciated. Or desired at all...To address the requirement for the
draggable
object to beresizable
as well, I don't think that this is possible, since bothdraggable()
andresizable()
respond to the same interaction. It may be possible, in some way, but it's currently beyond my ken, I'm afraid.Edited to add in the 'height/width' requirement, and also to tidy up a few things and improve the CSS. That said:
html:
css:
JS Fiddle demo, of the above.
You can get the width output with .resizable() and stop event. Try adding this:
You can try one of these:
or
The
.position()
method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with.offset()
, which retrieves the current position relative to the document.From http://api.jquery.com/position/