6

Estoy realizando un proyecto en el cual manejo drag y drop de JavaScript. Ahora ya tengo los divisores que se arrastran pero me piden que saque las coordenadas x,y de cada uno y ahí es donde está el problema: no sé cómo hacerlo pues al arrastrar cualquier div las coordenadas x,y toman el valor del último que se arrastró.

<!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>
2
  • En este momento cada vez que mueves un elemento estás pisando el valor de las coordenadas en los 4 inputs. ¿Dónde quieres almacenar los valores? ¿Quieres que un input guarde las coordenadas de un elemento, y el otro las del otro?
    – ffflabs
    el 1 mar. 2017 a las 18:08
  • exacto que cada uno tenga sus propios valores para guardarlos en una base de datos
    – json
    el 1 mar. 2017 a las 18:09

1 respuesta 1

6

Cuando termina el drag, se gatilla una función que recibe como parámetro el evento. Ese evento contiene el elemento que acabas de arrastrar. Está en event.target.

Una manera no muy elegante (pero rápida) de hacer lo que pides es hacer que los ID de cada input calcen con el ID del elemento más un sufijo (x e y). De esa manera, al soltar un elemento, leyendo su ID puedes saber qué inputs actualizar:

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 element = event.target;
    document.getElementById(element.id + 'x').value = element.getAttribute('data-x');
    document.getElementById(element.id + 'y').value = element.getAttribute('data-y');

  }

});

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 posiion attributes
  target.setAttribute('data-x', x);
  target.setAttribute('data-y', y);

}

// this is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener;
#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;
}
<script src="http://cdn.jsdelivr.net/interact.js/1.2.6/interact.min.js"></script>

<div id="drag-1" class="draggable" rel="1">
  <p> HC</p>
</div>

<div id="drag-2" class="draggable" rel="2">
  <p> PO</p>
</div>

<form id="form-ingreso">
  <label> Elemento 1
    <input type="text" id="drag-1x"  />
    <input type="text" id="drag-1y"  />
  </label>
  <br>
  <label> Elemento 2
    <input type="text" id="drag-2x"  />
    <input type="text" id="drag-2y"  />
  </label>
</form>

5
  • wow muchas gracias me has salvado amenadiel
    – json
    el 1 mar. 2017 a las 19:12
  • gracias por las ediciones y recomendaciones
    – json
    el 1 mar. 2017 a las 19:27
  • amenadiel me podrías proporcionar mas información acerca del tema ya que no sera la ultima vez que lo utilice
    – json
    el 1 mar. 2017 a las 19:49
  • Hmmm en realidad no tengo más información. El ponerle IDs que coincidieran fue una convención que se me ocurrió en el momento. De seguro hay mejores maneras. Y en cuanto al funcionamiento de interact, nunca había escuchado de esa librería, pero inspeccioné en la consola las propiedades de event y encontré la referencia al elemento dragable. Más allá de eso, cuenta con mi disposición cuando tengas más preguntas. A priori sigo sin saber qué hace interact más que mover cuadraditos.
    – ffflabs
    el 1 mar. 2017 a las 20:26
  • te lo agradezco amenadiel, así es del igual manera no he encontrado otro uso para interact solo que lo pidieron con esa libreria en especifico lo que me dejaron saber es que porque funciona bien con los moviles saludos
    – json
    el 1 mar. 2017 a las 21:49

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.