I am using draggabilly.js to make a group of divs draggable. The problem I have is in adding a dragend function to each div, so that I can see where it is at that end point.
My code is:
<script>
// get all draggie elements
var draggableElems = document.querySelectorAll('.draggable');
// array of Draggabillies
var draggies = []
// init Draggabillies
for ( var i=0, len = draggableElems.length; i < len; i++ ) {
var draggableElem = draggableElems[i]; console.log('i: '+i);
var draggie = new Draggabilly( draggableElem, {
containment: true
});
draggie.on('dragEnd', function() {
console.log( 'draggie at TP ' + draggie.position.x + ', ' + draggie.position.y ); });
draggies.push( draggie );
}
</script>
The problem is that only the last div in the for loop gives the correct values in the comment. In the console I see:
draggie at TP 120, 73
draggie at TP 201, 72
draggie at TP 188, 29
draggie at TP 225, 44
draggie at TP 225, 44
draggie at TP 225, 44
draggie at TP 184, 50
The first 4 comments reflect moving the last item to different positions, whereas the next 3 involve other (any other) item, and as can be seen, these other items just 'take on' the values of the previous one, while, the last comment results from going back to the original last item and moving it - with the correct comment resulting.
I can't see what I'm doing wrong. Any suggestions would be valued.
PhilB
The docs for this plugin show that the events (like dragEnd) carry with them the original event object, which can be used to access the item being dragged as well as the mouse position
draggie.on( 'dragEnd', function( event, pointer ) {...})
In your case, you will probably want the mouse location at dragEnd:
draggie.on('dragEnd', function(e, p) {
console.log(`dragEnd: X: ${p.pageX}, Y: ${p.pageY}` );
})
Codepen: https://codepen.io/javacado/pen/VwMzYjb?editors=1111