34

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.

Antti29
  • 2,953
  • 12
  • 34
  • 36
Pabuc
  • 5,528
  • 7
  • 37
  • 52
  • I've just answered what I *thought* your question was. But re-reading, I'm not so sure. Could you clarify what you want to find out? As I was *assuming* you wanted to have a continuous update of the `x`/`y` position of the object that you're dragging...I might not have answered your question at all. – David Thomas Feb 04 '11 at 22:28
  • David, actually what I need is a bit more complicated but you might do great help. What I want to do is to put a draggable object and a droppable image in a panel and drag the draggable object on the image and get the position of where it was dropped. I'll also need the draggable object to be resizable and get the size of it at the end too :) thank you – Pabuc Feb 04 '11 at 22:30

3 Answers3

79

You can use the drag event:

$('#dragThis').draggable({
    drag: function() {
        var offset = $(this).offset();
        var xPos = offset.left;
        var yPos = offset.top;
        $('#posX').text('x: ' + xPos);
        $('#posY').text('y: ' + yPos);
    }
});

JS Fiddle demo.

This demo brought to you by the drag event, and the methods offset() and text().


Edited in response to comment from OP, to original question:

David, actually what I need is a bit more complicated but you might do great help. What I want to do is to put a draggable object and a droppable image in a panel and drag the draggable object on the image and get the position of where it was dropped. I'll also need the draggable object to be resizable and get the size of it at the end too :) thank you

...uh, whoah...

I think this sort of covers the basics of what's asked for:

$('#dragThis').draggable( {
    containment: $('body'),
    drag: function() {
        var offset = $(this).offset();
        var xPos = offset.left;
        var yPos = offset.top;
        $('#posX').text('x: ' + xPos);
        $('#posY').text('y: ' + yPos);
    },
    stop: function() {
        var finalOffset = $(this).offset();
        var finalxPos = finalOffset.left;
        var finalyPos = finalOffset.top;

        $('#finalX').text('Final X: ' + finalxPos);
        $('#finalY').text('Final X: ' + finalyPos);
    },
    revert: 'invalid'
});

$('#dropHere').droppable({
    accept: '#dragThis',
    over: function() {
        $(this).animate({
            'border-width': '5px',
            'border-color': '#0f0'
        }, 500);
        $('#dragThis').draggable('option', 'containment', $(this));
    }
});

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 be resizable as well, I don't think that this is possible, since both draggable() and resizable() 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:

<div id="dragThis">
    <ul>
        <li id="posX">x: <span></span></li>
        <li id="posY">y: <span></span></li>
        <li id="finalX">Final X: <span></span></li>
        <li id="finalY">Final Y: <span></span></li>
        <li id="width">Width: <span></span></li>
        <li id="height">Height: <span></span></li>
    </ul>
</div>

<div id="dropHere"></div>

CSS:

#dragThis {
    width: 8em;
    height: 8em;
    padding: 0.5em;
    border: 3px solid #ccc;
    border-radius: 0 1em 1em 1em;
    background-color: #fff;
    background-color: rgba(255, 255, 255, 0.5);
}

#dragThis span {
    float: right;
}

#dragThis span:after {
    content: "px";
}

li {
    clear: both;
    border-bottom: 1px solid #ccc;
    line-height: 1.2em;
}

#dropHere {
    width: 12em;
    height: 12em;
    padding: 0.5em;
    border: 3px solid #f90;
    border-radius: 1em;
    margin: 0 auto;
}

jQuery:

$('#dragThis').draggable({
    containment: $('body'),
    drag: function() {
        var offset = $(this).offset();
        var xPos = offset.left;
        var yPos = offset.top;
        $('#posX > span').text(xPos);
        $('#posY > span').text(yPos);
    },
    stop: function() {
        var finalOffset = $(this).offset();
        var finalxPos = finalOffset.left;
        var finalyPos = finalOffset.top;

        $('#finalX > span').text(finalxPos);
        $('#finalY > span').text(finalyPos);
        $('#width > span').text($(this).width());
        $('#height > span').text($(this).height());
    },
    revert: 'invalid'
});

$('#dropHere').droppable({
    accept: '#dragThis',
    over: function() {
        $(this).animate({
            'border-width': '5px',
            'border-color': '#0f0'
        }, 500);
        $('#dragThis').draggable('option', 'containment', $(this));
    }
});

JS Fiddle demo, of the above.

Antti29
  • 2,953
  • 12
  • 34
  • 36
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Ca you please help me with the rest if you have time? Thanks David – Pabuc Feb 04 '11 at 22:37
  • @David, can you please make it resizable too :) Thank you! Greatly appreciated – Pabuc Feb 04 '11 at 23:01
  • @Pabuc, if you look at the final paragraph the answer is, sadly, "no, I can't." Mainly because both `draggable()` and `droppable()` respond to the same user-actions, and I can't find a way to differentiate between which plugin/method should be invoked. Possibly by nesting spans, or divs, within the element, but...I'm not convinced. Sorry =( – David Thomas Feb 04 '11 at 23:03
  • Okay then I have to find a workaround and the first one I can think of is, since I'll be letting users to enter text into the draggable object, Do you think that it is possible to get the length of the text and resize the draggable object? – Pabuc Feb 04 '11 at 23:06
  • @Pabuc: yep; that shouldn't be too hard. Though I'd suggest searching to see if others have already asked the question (or a similar question that you could build from) or, failing that, ask another question. I'm running out of space to add more information to this answer and, honestly, we're drifting a long way from your *original* question... =) – David Thomas Feb 04 '11 at 23:15
  • Thank you David. I've posted another question, http://stackoverflow.com/questions/4903863/resizable-droppable-object-in-jquery-possible . This might interest you too :) Thank you again – Pabuc Feb 04 '11 at 23:18
  • @Pabuc, so I see =) I think, however, that I'll concede defeat for this evening and go to bed...been a long day! Good luck with the next question (forgive my edit there, but I felt it might be useful for others to see this question as well) =D Oh, and incidentally I've shown (in my final edit as of writing) how to retrieve the `width` and `height` of the draggable object. – David Thomas Feb 04 '11 at 23:21
  • I know this is more than a year old, but it did exactly what i needed and in the easiest way. Thanks. – Austin Best Jul 03 '12 at 16:39
  • @AustinBest: age doesn't necessarily invalidate a solution! And you're very welcome, I'm glad that, even after quite a time, I was able to help out! =) – David Thomas Jul 03 '12 at 16:43
  • 1
    @SameeraPrasadJayasinghe: you’re very welcome indeed! – David Thomas Jun 27 '19 at 09:44
15

You can try one of these:

$(this).position()

or

$(this).offset()

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/

David B.
  • 5,700
  • 5
  • 31
  • 52
user603881
  • 151
  • 2
  • 1
    Hi, welcome to Stackoverflow! It's worth taking a read of the [Stackoverflow Markdown help page](http://stackoverflow.com/editing-help/) to get a feel for how to format your answers (for code blocks, and such) =) – David Thomas Feb 04 '11 at 23:16
0

You can get the width output with .resizable() and stop event. Try adding this:

$('#dragThis').resizable({ handles: "e, w",      
      stop: function(event, ui) {
        var width = ui.size.width;
        var height = ui.size.height;
    $('#width > span').text($(this).width());
    $('#height > span').text($(this).height());
      }
   });