I need to make a drag&drop for several pictures. I wrote a working code for one image.
const box = document.querySelector("#box");
const offset = {
x: null,
y: null
};
const getPosition = (e) => {
const pageX =
e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
const pageY =
e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
return {
pageX,
pageY
};
};
const mousemoveHandler = (e) => {
const { pageX, pageY } = getPosition(e);
box.style.left = pageX - offset.x + "px";
box.style.top = pageY - offset.y + "px";
};
const mousedownHandler = (e) => {
const { pageX, pageY } = getPosition(e);
const { x, y } = box.getBoundingClientRect();
const leftOffset = pageX - x;
const topOffset = pageY - y;
offset.x = leftOffset;
offset.y = topOffset;
window.addEventListener("mousemove", mousemoveHandler);
box.classList.add("active");
};
const mouseupListener = async () => {
window.removeEventListener("mousemove", mousemoveHandler);
box.classList.remove("active");
offset.x = null;
offset.y = null;
};
box.addEventListener("mousedown", mousedownHandler);
window.addEventListener("mouseup", mouseupListener);
box.ondragstart = function() {
return false;
};
If I change document.querySelector("#box") to document.querySelectorAll("#box") or document.querySelectorAll("section-one__img") so that the code works for all elements, then an error appears Uncaught TypeError: box.addEventListener is not a function