Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
JSFiddle[^]
in this code why is the 2 move blocks overlapping?? I don't understand.
Is there a problem in
JavaScript
document.querySelector('.move');
??
the orignal code is longer(200 lines) and a bit diffrent if you need i can Send it; This code is supposed for electron

What I have tried:

I didn't try much. cuz i couldn't understand the problem.
Posted
Updated 29-Jun-21 0:55am

1 solution

Here's an updated version of your demo, which should be slightly clearer:
Edit fiddle - JSFiddle - Code Playground[^]

The problem is with:
HTML
<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:
JavaScript
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[^]
 
Share this answer
 
Comments
Ɗααɳιടԋ Sყҽԃ 29-Jun-21 7:35am    
oh thanks now I can just use the z-index or divThatIsMoving.style.zIndex = 100; to bring forward the one in use.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900