Ashy
Ashy

Reputation: 21

JavaScript draggable elements inside div

I tried creating draggable elements inside a div until I came to a small issue is that I can't find a way to drag each element separately without affecting other elements, my code only handles one element with its id, here's my attempt

HTML

<div class="wrapper">
  <img id="imgPrime" src="" />
</div>

JS

const wrapper = document.querySelector(".wrapper"),
  header = wrapper.querySelector("#imgPrime");
function onDrag({movementX, movementY}){
  let getStyle = window.getComputedStyle(wrapper);
  let leftVal = parseInt(getStyle.left);
  let topVal = parseInt(getStyle.top);
  wrapper.style.left = `${leftVal + movementX}px`;
  wrapper.style.top = `${topVal + movementY}px`;
}
header.addEventListener("mousedown", ()=>{
  header.classList.add("active");
  header.addEventListener("mousemove", onDrag);
});
document.addEventListener("mouseup", ()=>{
  header.classList.remove("active");
  header.removeEventListener("mousemove", onDrag);
});

Css / if it helps

.wrapper{
  position: absolute;
  top: 50%;
  left: 50%;
  max-width: 350px;
  width: 300px;
  transform: translate(-50%, -50%);
  user-select: none;
}
.wrapper header.active{
  cursor: move;
  user-select: none;
}



#imgPrime{ display: none; 
   user-drag: none;  
   user-select: none;
   -moz-user-select: none;
   -webkit-user-drag: none;
   -webkit-user-select: none;
   -ms-user-select: none;
    max-width: 350px;
    width: 300px;
}

Upvotes: 1

Views: 1599

Answers (1)

Laaouatni Anas
Laaouatni Anas

Reputation: 3817

if you click the icon, then the icon will move (drag) with your cursor, when you dont click more the image (mouseup) the img remain in his place

const wrapper = document.querySelector(".wrapper");

const header = wrapper.querySelector("#imgPrime");

wrapper.addEventListener("mousedown", function() {
    document.onmousemove = function(e) {
        var x = e.clientX;
        var y = e.clientY;
        wrapper.position = "relative";
        wrapper.style.left = x + "px";
        wrapper.style.top = y + "px";
    };
});

document.addEventListener("mouseup", function() {
    document.onmousemove = null;
});
.wrapper {
    position: absolute;
    max-width: 350px;
    width: 300px;
    user-select: none;
}

.wrapper header.active {
    cursor: move;
    user-select: none;
}

#imgPrime {
    max-width: 50px;
    width: 50px;
}
<!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>
    <link rel="stylesheet" href="style.css">
    <script src="./script.js" defer></script>
</head>

<body>
    <div class="wrapper">
        <img id="imgPrime" src="https://img.itch.zone/aW1nLzcyNzgxNy5wbmc=/original/8AJNx%2B.png" />
    </div>
</body>

</html>

Upvotes: 1

Related Questions