хочу реализовать перемещение всех блоков на JS, т.е нажал на один квадрат вместе с ним перемещаются другие. Из того что есть:
Создаёт квадрат 20 на 20 пикселей, раскидывает его рандомно в документе.
function createCoub(className){
var div = document.createElement('div');
div.className = className;
div.style.width = '20px';
div.style.height = '20px';
div.style.backgroundColor = 'black'
div.style.margin = "0px"
div.style.position = "absolute";
div.style.top = Math.floor(Math.random() * (1500 - 0)) + 0 + "px";
div.style.left = Math.floor(Math.random() * (2000 - 0)) + 0 + "px"
return div;
}
Создаёт 50 таких блоков
for (var i = 0; i < 51; i++){
document.body.appendChild(createCoub('coub'));
}
И дальше идём сама проблема, брал код с javascript.learn, drug & drop, получается перетаскивать только 1 квадрат, который стоит первый в списке, пробовал перебирать их всех циклом и подставлять, но выдаёт ошибку, мол не может найти div[i].
function drag(){
var div = document.querySelector('.coub');
div.onmousedown = function(e) {
moveAt(e);
div.style.zIndex = 1000;
function moveAt(e) {
div.style.left = e.pageX - div.offsetWidth / 2 + 'px';
div.style.top = e.pageY - div.offsetHeight / 2 + 'px';
}
document.onmousemove = function(e) {
moveAt(e);
}
div.onmouseup = function() {
document.onmousemove = null;
div.onmouseup = null;
}
}}
drag();