What I wanted: a div “dragItem” should be moved horizontally.
If the mouse cursor is on top of a div with the class “tag”, then the position of “dragItem” will be changed.
Actually this is working. But I got a strange behavior, when I release my mouse button while the cursor is not in the same horizontal row as where it started moving:
next time I click on “dragItem” I can’t see the movement until I relaese the mouse button.
AND: after I released the mouse button, I am still able to move “dragItem” around.
I don’t understand why this happens. While trying to debug it, I found out, that – if I click somewhere on the screen before clicking on “dragItem” – things work as expected. But why?
dragItem = document.getElementById("dragItem")
dragItem.addEventListener('mousedown', dragMouseDownHandler)
mouseIsDown = false;
function dragMouseDownHandler(event) {
if (!mouseIsDown) {
mouseIsDown = true;
document.addEventListener('mousemove', mouseMove)
document.addEventListener('mouseup', mouseUp)
}
}
function mouseMove(event) {
var elementsUnderMouse = document.elementsFromPoint(event.clientX, event.clientY);
elementsUnderMouse.forEach(element => {
if (element.classList.contains("tag")) {
vonLinks = element.offsetLeft
dragItem.style.left = vonLinks + 'px'
}
})
}
function mouseUp(event) {
mouseIsDown = false;
document.removeEventListener('mousemove', mouseMove)
document.removeEventListener('mouseup', mouseUp)
}
#moveArea {
width: 600px;
height: 600px;
background-color: lightgray;
display: flex;
flex-direction: column;
}
.row {
display: flex;
flex-direction: row;
}
.tag {
height: 110px;
width: 110px;
background-color: #b3d4fc;
border: 1px solid black;
}
#dragItem {
height: 100px;
width: 100px;
background-color: lightcoral;
position: fixed;
}
<div id="moveArea">
<div class="row">
<div class="tag">
<div id="dragItem"></div>
</div>
<div class="tag"></div>
<div class="tag"></div>
<div class="tag"></div>
</div>
<div class="row">
<div class="tag"></div>
<div class="tag"></div>
<div class="tag"></div>
<div class="tag"></div>
</div>
</div>
Demo of JS mousemove problem