Javascript (mouse event listeners) - Elements jump away and do not properly follow mouse

104 Views Asked by At

Good Evening,

I have a problem that I've been working on for 2 days now, and have been unable to solve. I'll get right to it.

I have several rows of elements of the same class inside of a container element. The goal is to click and hold mousedown on any of the rows and move them around the screen with the mouse. The problem is that after the first row, elements begin to wildly drop away from the mouse when trying to move said elements.

This is not only a problem with elements of the same class inside of a container element, but I have also found this problem whenever I try to mousedown and move any element that is not the first element in the document. Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<style>

#container{
    display:inline-block;
    border: 2px black solid;
    padding-top: 5px;
    padding-left: 5px;
    padding-right: 5px;
}

.rows{
    border: 1px red solid;
    width: 50px;
    height: 50px;
    margin-bottom: 5px;
}
    

</style>

<body>
    <div id="container">
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>
        <div class="rows"></div>  
    </div>
</body>

<script>
    
let rows = document.querySelectorAll('.rows');
let container = document.getElementById('container');

let x = 0;
let y = 0;

for(let i = 0; i < rows.length; i++){

    rows[i].addEventListener('mousedown', grabElement);
    rows[i].addEventListener('mouseup', stopMoving);

    function grabElement(){
    rows[i].addEventListener('mousemove', mouseMove);
    }

    function mouseMove(e){
        x = e.clientX;
        y = e.clientY;
        rows[i].style.transform = `translate(${x-25}px, ${y-25}px)`;
    }

    function stopMoving(){
    rows[i].removeEventListener('mousemove', mouseMove);
    }
}
 
</script>

</html>
0

There are 0 best solutions below