I am doing a project in which I handle drag and drop of JavaScript
. Now I already have the dividers that are dragged but they ask me to get the coordinates x,y
of each one and that is where the problem is: I don't know how to do it because when dragging any div
the coordinates x,y
take the value of the last one that was dragged.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Drag and Drop</title>
<style>
#drag-1, #drag-2 {
width: 3px;
height: 5px;
background-color: #29e;
color: white;
border-radius: 0.75em;
padding:3%;
-webkit-transform: translate(0px, 0px);
transform: translate(0px, 0px);
}
#drag-me::before {
content: "#" attr(id);
font-weight: bold;
}
</style>
</head>
<body>
<div id="drag-1" class="draggable">
<p> HC</p>
</div>
<div id="drag-2" class="draggable">
<p> PO</p>
</div>
<form id="form-ingreso">
<input type="text" id="x" />
<input type="text" id="y" />
<input type="text" id="x1" />
<input type="text" id="y1" />
</form>
<script src="js/interact.js"></script>
<script src="js/interact.min.js"></script>
<script>
interact('.draggable').draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
// enable autoScroll
autoScroll: true,
// call this function on every dragmove event
onmove: dragMoveListener,
// call this function on every dragend event
onend: function (event) {
var A = event.dx;
var B = event.dy;
var x1 = event.dx;
var y1 = event.dy;
document.getElementById('x').value = A;
document.getElementById('y').value = B;
document.getElementById('x1').value = x1;
document.getElementById('y1').value = y1;
}
});
function dragMoveListener (event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
// update the position attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
// this is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener;
</script>
</body>
</html>
When the drag ends, a function is triggered that receives the event as a parameter. That event contains the element you just dragged. It's in
event.target
.A not very elegant (but quick) way to do what you're asking for is to make the IDs of each input match the element's ID plus a suffix (x and y). That way, when dropping an element, by reading its ID you can tell which inputs to update: