I have 2 divs and I want to make them both draggable using one set of code, so whichever one that is clicked can be dragged across the screen At the moment, only one is draggable. How do I fix this?
<div class="mydiv">
<div class="mydivheader">Click here to move</div>
</div>
<div class="mydiv">
<div class="mydivheader">Click here to move</div>
</div>
let mydivs = document.getElementsByClassName("mydiv")
for (mydiv of mydivs) {
mydiv = mydiv
}
dragElement(mydiv);
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
elmnt.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}
In your code mydiv = mydiv
creates a global variable which is overwrite every iteration.
You need to move the call to dragElement
inside the loop. Like so...
for (mydiv of mydivs) {
dragElement(mydiv);
}