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

146
Views
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
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!