Here's an updated version of your demo, which should be slightly clearer:
Edit fiddle - JSFiddle - Code Playground[
^]
The problem is with:
<div class="line" />
The
div
element is not an empty element; you cannot declare it as a self-closing tag.
If you inspect the DOM in your browser's developer tools, you will see that both
<div class="line">
elements are left open, and all subsequent elements become descendants of those elements. Therefore, the second
<div class="move">
element is a descendant of the first
<div class="move">
element, and will be moved with it.
If you use the proper closing tag for the
<div class="line">
, the "move" elements remain separate:
Updated demo[
^]
However, you will now face the problem that the event handler is only attached to the first "move" element, which is now completely hidden behind the second "move" element.
Assuming you want to be able to move both elements separately, you will need to change your Javascript to account for multiple elements. For example:
let x = 0, y = 0, divThatIsMoving = null;
document.querySelectorAll('.move').forEach(div => {
div.addEventListener('mousedown', function(e){
divThatIsMoving = div;
x = div.offsetLeft - e.clientX;
y = div.offsetTop - e.clientY;
}, true);
div.addEventListener('mouseup', function(e){
divThatIsMoving = null;
}, true);
});
const elem = document.querySelector('.wrapper');
elem.addEventListener('mousemove', function(e){
if (divThatIsMoving) {
divThatIsMoving.style.left = (e.clientX + x) + 'px';
divThatIsMoving.style.top = (e.clientY + y) + 'px';
}
}, true);
Updated demo[
^]