Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda