catcool
catcool

Reputation: 51

how to get xy coordinate of an image after drag and drop in jquery?

I have a problem getting the x y coordinates of a rectangle.

Actually I already get the x y coordinate, but it is not correct.. I used visual studio 2008.. n using jquery..ok, the design is like this:

I had a div name "drg".. that is a big box.. inside the div(the big box) there is an image that is the rectangle. I drag the rectangle to the end top left of the div but the result for x=8, n y=8.. Logically the code counts from the out of the div.. Thats why got x=10 n y=10.

I want when drag to the end top left of the div, the result must be x=0,y=0..

This is my code: "im" is the id of image(red box)

$(document).ready(function() {
    // sets draggable the elements with id="im"
    $('#im').draggable({
        cursor: 'move',        // sets the cursor apperance
        containment: '#drg', 

        stop : function(){
            $("#value").text('x-axis :' + $('#im').offset().left + 'y-axis :' + $('#im').offset().top);

            var imgPosX = 10 - $("img#im").width();
            var imgPosY = 10 - $("img#im").height();

        }
    });
});

When I drag the image(red box)to the top left, it get x=8,y=8...it counts from out of the blue box..I want it to count from in the blue box n get x=0,y=0 if the position of the image(red box) is like that.

Upvotes: 3

Views: 4116

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

stop: function(event, ui) {

        // Show dropped position.
        var Stoppos = $(this).position();
        var left = Math.abs(Stoppos.left);
        var top = Math.abs(Stoppos.top);
    }

You can also make it within drag() event like

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

Complete demo with above two events

According to comment

As you don't want negative value so use Math.abs() to make all value positive.

Upvotes: 3

Related Questions