JQuery-UI Draggable: print coordinate relative to DIV container

This demo shows how to dispatch an event when dragging a component around using jQuery. I have a component inside a DIV , and when I drag this component, I want to print the coordinate of the relative component in the DIV container, can any jQuery pro help me 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 drag and drop callback event, I need to find out pageX, pageY , as well as offsetX, offsetY , to find out the relative position of the component when dragging and dropping. I am very new to jQuery. I know that I can get 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'm not sure how to combine them.

+6
source share
2 answers

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); } }); });​ 
+14
source

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

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

+7
source

Source: https://habr.com/ru/post/887143/


All Articles