Drag and Drop List Using TypeScript (original) (raw)

Last Updated : 05 Feb, 2025

A drag-and-drop sortable list in TypeScript lets users reorder items by dragging them to new positions. This is done using dragstart, dragend and dragover events for smooth DOM manipulation.

What We’re Going to Create

We’ll build a drag-and-drop sortable list with features like handling dragstart, dragover, and dragend events to interact with DOM elements.

**Project Preview

Screenshot-2025-01-27-160838

Drag and Drop Sortable List in Typescript

Drag and Drop sortable List - HTML and CSS code

This HTML and CSS code creates a stylish, interactive drag-and-drop sortable list. It uses smooth transitions and visual feedback for reordering items within a container, making the list both functional and visually appealing.

HTML `

Drag and Drop Sortable List

`

**In this example

Drag and Drop sortable list – TypeScript Logic

This code implements a drag-and-drop sortable list where items can be rearranged through a smooth drag-and-drop interface. Using JavaScript and TypeScript, it leverages event listeners and DOM manipulation to update the list dynamically.

JavaScript `

const list = document.querySelector('.list') as HTMLElement | null; let dragging: HTMLElement | null = null;

if (list) { list.addEventListener('dragstart', (e: DragEvent) => { const target = e.target as HTMLElement; if (target && target.classList.contains('item')) { dragging = target; target.classList.add('dragging'); } });

list.addEventListener('dragend', () => {
    if (dragging) {
        dragging.classList.remove('dragging');
    }
    document.querySelectorAll('.item').
        forEach(item => item.classList.remove('over'));
    dragging = null;
});

list.addEventListener('dragover', (e: DragEvent) => {
    e.preventDefault();
    const afterElement = getDragAfterElement(list, e.clientY);

    document.querySelectorAll('.item')
        .forEach(item => item.classList.remove('over'));

    if (afterElement && dragging) {
        afterElement.classList.add('over');
        list.insertBefore(dragging, afterElement);
    } else if (dragging) {
        list.appendChild(dragging);
    }
});

}

function getDragAfterElement(container: HTMLElement, y: number): HTMLElement | null { const items = Array.prototype.slice.call(container.querySelectorAll ('.item:not(.dragging)')) as HTMLElement[];

return items.reduce((closest, child) => {
    const box = child.getBoundingClientRect();
    const offset = y - box.top - box.height / 2;
    if (offset < 0 && offset > closest.offset) {
        return { offset, element: child };
    }
    return closest;
}, { offset: Number.NEGATIVE_INFINITY, element: null }).element;

}

`

**In this example

Convert to JavaScript File

Now You need to convert the TypeScript file into JavaScript to render by browser. Use one of the following command.

npx tsc lists.ts
tsc lists.ts

Complete Code

HTML `

Drag and Drop Sortable List

`