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();" />