Search code examples
javascriptjqueryjquery-uidraggable

Jquery-ui Save position of draggable item


I want to keep the var of the x and y position of the draggable item on stop. Thank to some fiddle and topic i did this :

$("#image").draggable({
        helper: 'clone',
    stop:function(event,ui) {
        var wrapper = $("#wrapper").offset();
        var borderLeft = parseInt($("#wrapper").css("border-left-width"),10);
        var borderTop = parseInt($("#wrapper").css("border-top-width"),10);
        var pos = ui.helper.offset();
        $("#source_x").val(pos.left - wrapper.left - borderLeft);
        $("#source_y").val(pos.top - wrapper.top - borderTop);
        alert($("#source_x").val() + "," + $("#source_y").val());
    }
});

I just want to save the position each time I move the item and use it in an other javascript function.

Here is the fiddle.js :

http://jsfiddle.net/oe0fg84b/


Solution

  • As mentioned by @John, it looks like you're already storing the x and y coordinates of the draggable image in elements #source_x and #source_y, respectively.

    You should be able to access them in another function as follows:

    var x =$("#source_x").val(); 
    var y = $("#source_y").val();
    

    Just an observation, your helper property clone seems to be causing the image to reset it's position after being dragged. I suspect this is then overriding your coordinate values, resetting to 0,0 each time. Try:

    $("#image").draggable({
    stop:function(event,ui) {
        var wrapper = $("#wrapper").offset();
        var borderLeft = parseInt($("#wrapper").css("border-left-width"),10);
        var borderTop = parseInt($("#wrapper").css("border-top-width"),10);
        var pos = ui.helper.offset();
        $("#source_x").val(pos.left - wrapper.left - borderLeft);
        $("#source_y").val(pos.top - wrapper.top - borderTop);
        alert($("#source_x").val() + "," + $("#source_y").val());
        }
    });
    

    I've modified your example to later get the coordinates upon button click: http://jsfiddle.net/Jason_Graham/oe0fg84b/2/