6

This demo shows how send event when dragging the component around using jQuery. I have a component inside a DIV, and when I drag that component I want to print out the coordinate of the component relative to the DIV container, can any jQuery pro help me out here. Here is what I got so far.

<div id="container" style="width: 400px; height: 4000px; border: 1px solid black;" > <div id="draggable" style="width: 150px; height: 150px; background-color: black; cursor: move;"> <div class="count"/> </div> </div> <script> jQuery(function(){ jQuery("#draggable").draggable({ containment: "#contain", scroll: false, drag: function(){ } }); function updateCoordinate(newCoordinate){ jQuery(".count").text(newCoordinate); } }); </script> 

In the callback event for drag, I need to figure out the pageX, pageY as well as the offsetX, offsetY to find out the relative position of the component when i drag. I am very new to jQuery. I know that I can obtain the both pageX, pageY and offsetX, offsetY like this

jQuery("#container").click(function(event){ var offset = jQuery(this).offset(); var pageX = event.pageX; var pageY = event.pageY; }); 

but I am not sure how to combine them together.

2 Answers 2

14

Like this?

http://jsfiddle.net/aasFx/36/

$(function() { $("#draggable").draggable({ containment: "#contain", scroll: false, drag: function() { var $this = $(this); var thisPos = $this.position(); var parentPos = $this.parent().position(); var x = thisPos.left - parentPos.left; var y = thisPos.top - parentPos.top; $this.text(x + ", " + y); } }); });​ 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Take a look at drowe solution as well. I think it really clean.
10

What you might want to do is set the parent container CSS to 'position: relative', and the 'draggable item' to 'position: absolute'. Then, using things like $(this).position().left / top will be relative to the parent container.

See here: http://jsfiddle.net/bTULc/1/

2 Comments

I like your solution a lot but kingjiv answered first, so I have to accept his answer. Thank you very much, btw. +1
Worked like a charm :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.