SammyMe
SammyMe

Reputation: 85

How to get distance in pixels of element inside of parent div

so I'm using Jquery and pure js to write small application, I have a element inside of a div parent.This Draggable element (ui widget) that can be moved around in div parent.I would like to get exact amount of pixels from the top and from the left.

This is what I mean: enter image description here

I have following code right now, but with this code I can't get exact ammount of pixels from top and bottom,

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

Working example: http://jsfiddle.net/8fbdf93m/

Please help.

Upvotes: 2

Views: 1078

Answers (2)

ram hemasri
ram hemasri

Reputation: 1634

you can also try $(this).css('left') or $(this).css('top')

updated fiddle http://jsfiddle.net/8fbdf93m/4/

Upvotes: 1

murrometz
murrometz

Reputation: 904

Try Jquery.Position method. It allows you to retrieve the current position of an element relative to the offset parent

Upvotes: 1

Related Questions