Search code examples
javascriptdrag-and-drop

How to make Drag and Drop work Horizontally?


I'm trying to get Drag and Drop to work correctly

But in the image gallery, it only changes the position of the photo when dragging it under the other image

As if it only works vertically

Demo

Javascript Vanilla

const enableDragSort = className => {
    // Gets all child elements of the .gallery or .datasheet class
    [...document.getElementsByClassName(className)].forEach(enableDragList);
}

const enableDragList = className => {
    // For each child of the class, add the draggable attribute
    [...className.children].forEach(enableDragItem);
}

const enableDragItem = item => {
    item.setAttribute('draggable', true);
    item.ondrag = handleDrag;
    item.ondragend = handleDrop;
}

const handleDrag = event => {
    const item = event.target.closest('[draggable]');
    item.classList.add('drag-sort-active');

    // .gallery or .datasheet
    const className = item.parentElement;

    const x = event.clientX;
    const y = event.clientY;

    let swap = document.elementFromPoint(x, y) ?? item;

    if (className === swap.parentElement) {
        swap = (swap !== item.nextSibling) ? swap : swap.nextSibling;

        className.insertBefore(item, swap);
    }
}

const handleDrop = ({ target }) => {
    const item = target.closest('[draggable]');
    item.classList.remove('drag-sort-active');
}

// Drag Drop
enableDragSort('gallery'); // It does not work properly
enableDragSort('datasheet'); // It works

Solution

  • The problem is that you are adding attribute draggable to div wrapper, not the image itself. That means you need to drag over the div to make it work.

    The quickest solution I come up is adding property pointer-events: none; to .picture img styles.

    .picture img {
        min-width: 100px;
        height: 125px;
        object-fit: contain;
        border: 5px solid transparent;
        pointer-events: none; // add this line
    }
    

    What it does, (in short) it makes the img "transparent" for the mouse events.