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

148
Visualizações
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 à 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