HOW TO DRAG AND DROP ELEMENTS
Sep 02, 2022 Copy Link
السلام عليكم 👋
تعالوا نشوف النهاردة إزاي نقدر نعمل drag & drop لل elements 🧐
أولاً لازم نضيف draggable=true لل element اللي هعمله drag & drop و كمان هنديله إسم كلاس مُعبر عشان نستخدمه بعدين زي الإسم دا element-dragged-dropped 🤙
ثانياً هنضيف كل element من دول جوا parent خاص بيه, و هنعرف ليه عملنا كدا .. تعالوا يلا عشان نشوف الكود هيكون شكله إيه 😋
const items = document.querySelectorAll('.element-dragged-dropped');
items.forEach(item => {
item.addEventListener('dragstart', dragStart);
});
function dragStart(e) {
e.dataTransfer.setData('text/plain', e.target.id);
}
/* drop targets */
const boxes = document.querySelectorAll('.parent-dragged-dropped-elements');
boxes.forEach(box => {
box.style.cursor = "pointer";
box.addEventListener('dragenter', dragEnter)
box.addEventListener('dragover', dragOver);
box.addEventListener('dragleave', dragLeave);
box.addEventListener('drop', drop);
});
function dragEnter(e) {
e.preventDefault();
if (e.target.classList[0] == "element-dragged-dropped") {
e.target.classList.add('drag-over');
}
}
function dragOver(e) {
e.preventDefault();
if (e.target.classList[0] == "element-dragged-dropped") {
e.target.classList.add('drag-over');
}
}
function dragLeave(e) {
e.target.classList.remove('drag-over');
}
function drop(e) {
e.target.classList.remove('drag-over');
// get the draggable element
const id = e.dataTransfer.getData('text/plain');
const draggable = document.getElementById(id);
// add it to the drop target
if (e.target.classList[0] == "element-dragged-dropped") {
e.target.previousSibling.parentElement.after(draggable.previousSibling.parentElement);
}
}
يلا بينا نشرح الكود اللي فات دا 😋
أولاً إحنا جبنا كل ال elements اللي ليها كلاس element-dragged-dropped و عملنا لوب عليهم عشان نديلهم event ال dragstart و نفس الكلام دا مع ال parent الخاص بكل element و كمان زودنا علي ال events جزء خاص بال styling بحيث إنه يظهر hand أثناء عملية ال drag & drop و في كل ال functions عدا dragLeave كنت بعمل check علي ال element اللي بعمله drag & drop لو ليه إسم كلاس مُعين بديله كلاس من عندي -هنشوفه بعدين- بعرف إن دا هو اللي بيحصله drag و في علملية ال drop كنت بعمل نفس الحاجة و بجيب ال parent بتاع ال element دا عشان أضيف ال element دا بعده و عشان كدا ضيفنا ال parent 😎
و دلوقتي هنشوف الكلاس اللي كنا بنضيفه لل element عشان يخلي شكله جميل 🤩
.drag-over {
border: dashed 3px gray;
}
و بكدا أكون خلصت و أتمني تكون إستفدت ✔