jQuery: getting the coordinates of a draggable object

by gabrieleromanato

HTML

<div id="canvas">
<div id="box"></div>
</div>

<div id="results"></div>

CSS

#canvas {
    width: 500px;
    height: 400px;
    background: #ccc;
    position: relative;
    margin: 2em auto;
}

#box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background: green;
    cursor: move;
}

#results {
    text-align: center;
}

JavaScript

var coordinates = function(element) {
    element = $(element);
    var top = element.position().top;
    var left = element.position().left;
    $('#results').text('X: ' + left + ' ' + 'Y: ' + top);
}


$('#box').draggable({
    start: function() {
        coordinates('#box');
    },
    stop: function() {
        coordinates('#box');
    }
});