Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
How to add function to div with javascript

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!