Drag & Drop

드래그앤드랍을 만들어 보겠습니다.

드래그 개념

mousedown

  • 드래그 가능한 요소에 마우스를 눌렀을 때(mousedown) 이벤트 입니다.
  • 드래그 시작한 요소의 복사본 두 개 생성되어, 하나는 원래 위치에 그대로 붙고 다른 하나는 body에 붙습니다.
    (원래 위치에 그대로 붙는 복사본은 옮길 요소의 시각적인 표현 등에 사용됩니다. )

mousemove

  • 마우스를 누르고 움직일 때(mousemove) 이벤트 입니다.
  • 현재 마우스 좌표를 따라 body에 붙은 복사본을 이동 시킵니다.
  • 마우스 좌표가 이동할 박스이거나 이미 드래그된 아이템 위로 옮겨졌을 경우 인디게이터들을 표시해 줍니다.

mouseup

  • 마우스를 떼었을 때(mouseup) 이벤트 입니다.
  • 마우스를 뗀 좌표가 이동할 박스이거나 드래그 된 아이템 위 여부를 체크하여 맞는 위치에 위치시킵니다.
  • 이후 관련 이벤트나 변수 등을 정리합니다.

Source

html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<ul
class="max-w-[848px] select-none gap-3 grid grid-cols-4"
id="source-list"
>
<li
class="drag-item px-4 py-3 bg-blue-50 rounded cursor-pointer shadow transition-transform duration-500"
>
<header class="flex justify-between text-md">
<h2>Korea</h2>
<strong>+</strong>
</header>
<figure class="mt-3 rounded overflow-hidden">
<img src="https://picsum.photos/seed/4/300/300" alt="Korea" />
</figure>
</li>
<li
class="drag-item px-4 py-3 bg-blue-50 rounded cursor-pointer shadow transition-transform duration-500"
>
<header class="flex justify-between text-md">
<h2>Japan</h2>
<strong>+</strong>
</header>
<figure class="mt-3 rounded overflow-hidden">
<img src="https://picsum.photos/seed/3/300/300" alt="Japan" />
</figure>
</li>
</ul>
Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
<script>
const dragState = {
originalItem: null,
placeholder: null,
cloneItem: null,
indicator: null,
animationFrame: null,
};

const dropbox = document.getElementById("dropbox");

// 플레이스홀더 생성
function createPlaceholder(item) {
const placeholder = item.cloneNode(true);
placeholder.style.pointerEvents = "none";
placeholder.style.display = "none";
item.parentNode.insertBefore(placeholder, item.nextSibling);
return placeholder;
}

// 드래그 중인 복제 아이템 생성
function createClone(item) {
const clone = item.cloneNode(true);
clone.classList.add("dragging");
clone.style.position = "fixed";
clone.style.pointerEvents = "none";
clone.style.zIndex = "9999";
document.body.appendChild(clone);
return clone;
}

// 복제 아이템 위치 업데이트
function updateClonePosition(clone, x, y) {
if (clone) {
clone.style.left = `${x + 5}px`;
clone.style.top = `${y + 5}px`;
}
}

// 삽입 위치 인디케이터 표시
function showInsertIndicator(mouseX, targetItem) {
const dropRect = dropbox.getBoundingClientRect();
const targetRect = targetItem.getBoundingClientRect();
const insertBefore = mouseX < targetRect.left + targetRect.width / 2;

if (!dragState.indicator) {
dragState.indicator = document.createElement("div");
dragState.indicator.className = "drop-indicator";
dropbox.appendChild(dragState.indicator);
}

if (dragState.animationFrame) {
cancelAnimationFrame(dragState.animationFrame);
}

dragState.animationFrame = requestAnimationFrame(() => {
const left = insertBefore
? targetRect.left - dropRect.left - 8
: targetRect.right - dropRect.left + 4;

dragState.indicator.style.left = `${left}px`;
dropbox.insertBefore(
dragState.indicator,
insertBefore ? targetItem : targetItem.nextSibling
);
});
}

// 인디케이터 제거
function removeIndicator() {
if (dragState.indicator) {
dragState.indicator.remove();
dragState.indicator = null;
}
if (dragState.animationFrame) {
cancelAnimationFrame(dragState.animationFrame);
dragState.animationFrame = null;
}
}

// 드롭박스로 아이템 이동
function moveItemToDropbox(mouseX, mouseY) {
const elementBelow = document.elementFromPoint(mouseX, mouseY);
const targetItem = elementBelow?.closest(".draged-item");

if (targetItem) {
const targetRect = targetItem.getBoundingClientRect();
const insertBefore = mouseX < targetRect.left + targetRect.width / 2;

dropbox.insertBefore(
dragState.originalItem,
insertBefore ? targetItem : targetItem.nextSibling
);
} else {
dropbox.appendChild(dragState.originalItem);
}

dragState.originalItem.classList.add("draged-item");
}

// 원래 위치로 복원
function restoreItem() {
if (dragState.placeholder) {
dragState.placeholder.replaceWith(dragState.originalItem);
}
}

// 상태 초기화
function cleanup() {
dropbox.classList.remove("drag-over");

if (dragState.cloneItem) {
dragState.cloneItem.remove();
}

if (dragState.placeholder) {
dragState.placeholder.remove();
}

removeIndicator();

dragState.originalItem = null;
dragState.placeholder = null;
dragState.cloneItem = null;
}

// 드래그 중 이벤트
function handleDragMove(e) {
e.preventDefault();

updateClonePosition(dragState.cloneItem, e.clientX, e.clientY);

const elementBelow = document.elementFromPoint(e.clientX, e.clientY);
const isOverDropbox = elementBelow?.closest("#dropbox");
const targetItem = elementBelow?.closest(".draged-item");

if (isOverDropbox) {
const hasItems = dropbox.querySelector(".draged-item");

if (hasItems && targetItem) {
showInsertIndicator(e.clientX, targetItem);
} else if (!hasItems) {
dropbox.classList.add("drag-over");
removeIndicator();
}
} else {
dropbox.classList.remove("drag-over");
removeIndicator();
}
}

// 드래그 종료 이벤트
function handleDragEnd(e) {
e.preventDefault();

document.removeEventListener("mousemove", handleDragMove);
document.removeEventListener("mouseup", handleDragEnd);

const rect = dropbox.getBoundingClientRect();
const isInsideDropbox =
e.clientX >= rect.left &&
e.clientX <= rect.right &&
e.clientY >= rect.top &&
e.clientY <= rect.bottom;

if (isInsideDropbox) {
moveItemToDropbox(e.clientX, e.clientY);
} else {
restoreItem();
}

cleanup();
}

// 드래그 시작 이벤트
function handleDragStart(e) {
e.preventDefault();

dragState.originalItem = e.currentTarget;
dragState.placeholder = createPlaceholder(dragState.originalItem);
dragState.cloneItem = createClone(dragState.originalItem);

document.addEventListener("mousemove", handleDragMove);
document.addEventListener("mouseup", handleDragEnd);
}

// 초기화
function init() {
const items = document.querySelectorAll(".drag-item");
items.forEach((item) => {
item.addEventListener("mousedown", handleDragStart);
});
}

init();
</script>
Result