Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
movement capability for each created div

How can I write in a structure that I can move each div I create as I press the button?

In this example code I run, when I move the divs after adding them, they all move at the same time.

It is necessary to make an addlistener that will work according to the different IDs of each created div.

var mousePosition;
var offset = [0, 0];
var div;
var isDown = false;
var count = 5;

function doFunction() {

  count = count + 1;

  let id = "id_";
  var div = document.createElement('div');

  divID = id + count;
  div.id = divID;
  div.className = 'box';
  document.body.appendChild(div);
  add(div);
}

function add(div) {

  var divID = div.id;

  addEventListener('mousedown', function(e) {
    isDown = true;
    offset = [div.offsetLeft - e.clientX, div.offsetTop - e.clientY];
    //console.log(offset);
  });

  document.addEventListener('mouseup', function() {
    isDown = false;
  });
  document.addEventListener('mousemove', function(event) {
    event.preventDefault();
    if (isDown) {

      mousePosition = {

        x: event.clientX,
        y: event.clientY

      };
      div.style.left = (mousePosition.x + offset[0]) + 'px';
      div.style.top = (mousePosition.y + offset[1]) + 'px';
    }
  });
}
body {
    font-family: sans-serif;
  }
  
  .box {
    height: 200px;
    width: 200px;
    background-color: black;
    cursor: move;
    position: absolute;
  }
  
  .box:active {
    background-color: aquamarine;
    opacity: 0.8;
  }
  
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda