FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

JavaScript Drag & Drop

on in JavaScript DOM
Last modified on

Here’s a nice list of plain JavaScript dragging and dropping solutions. They are minimal, as they serve as proof of concept, and they can be easily extended.

Solution #1: JavaScript Card Sorting

This first solution uses basic HTML5 events to drag and drop elements (basically switching places). See a JavaScript sorting demo and check the code below.

Add the elements and add a droptarget class to each of them.

<p>Sort these cards into your order of preference:</p>

<ul class="sortable">
    <li class="droptarget" data-id="184">? Apples</li>
    <li class="droptarget" data-id="454">? Oranges</li>
    <li class="droptarget" data-id="558">? Bananas</li>
    <li class="droptarget" data-id="1247">? Strawberries</li>
</ul>

Add the styling for the draggable elements (see the demo for more styles):

[draggable] {
    user-select: none;
}
[draggable]:hover {
    outline: 3px solid #009432;
}

Add the JavaScript. Note that a serialisedData string is being returned, if you need to save the current state of the items.

if (document.querySelector('.droptarget')) {
    let source;

    [].forEach.call(document.querySelectorAll('.droptarget'), sortable => {
        sortable.draggable = true;

        sortable.ondragstart = event => {
            dragStarted(event);
        };
        sortable.ondragover = event => {
            event.preventDefault();
            event.dataTransfer.dropEffect = 'move';
        };
        sortable.ondragenter = event => {
            event.target.style.outline = "3px solid #0652DD";
        };
        sortable.ondragleave = event => {
            event.target.style.outline = "";
        };
        sortable.ondrop = event => {
            dropped(event);
        };
    });
}


function dragStarted(event) {
    source = event.target;

    event.dataTransfer.setData('text/plain', event.target.innerHTML);
    event.dataTransfer.effectAllowed = 'move';
}

function dropped(event) {
    event.preventDefault();
    event.stopPropagation();

    // update text in dragged item
    source.innerHTML = event.target.innerHTML;
    event.target.style.outline = "";

    // update text in drop target
    event.target.innerHTML = event.dataTransfer.getData('text/plain');

    let elements = document.getElementsByTagName('li'),
        serialisedData = '';

    for (let i = 0; i < elements.length; i++) {
        serialisedData += `listItem[]=${elements[i].dataset.id}&`;
    }
    console.log(serialisedData);
}

Solution #2: JavaScript Dragging & Dropping

This example comes from MDN Web Docs. See a JavaScript draggable elements demo. I used this example for a mini quiz game where the user was suppose to drag the correct answer in the form of a visual icon over a parent element.

Solution #3: Simulated Dragging & Dropping

Why simulated? Because it only uses mouseup, mousemove and mousedown events to simulate dragging by detecting the mouse position relative to draggable/droppable elements. See a JavaScript drag & drop demo and check the code below.

Add the HTML:

<div class="DragContainer">
    <div class="DragBox" id="Item1" dragclass="DragDragBox">Item #1</div>
    <div class="DragBox" id="Item2" dragclass="DragDragBox">Item #2</div>
    <div class="DragBox" id="Item3" dragclass="DragDragBox">Item #3</div>
    <div class="DragBox" id="Item4" dragclass="DragDragBox">Item #4</div>
</div>

Add the styling for the draggable elements:

.DragContainer {
    position: relative;
    border: #669999 2px solid;
    padding: 8px;
    margin: 8px;
}
.DragBox {
    border: #000 1px solid;
    padding: 8px 24px;
    margin-bottom: 4px;
    cursor: pointer;
    background-color: #eeeeee;
    transition: all 0.25s ease-out;
}
.DragBox:hover {
    background-color: #ffff99;
}
.DragHelper {
    border: 1px dotted red;
    transform: scale(1.1);
    transition: all 0.15s ease-out;
}
.DragDragBox {
    border: #000 1px solid;
    padding: 8px;
    margin-bottom: 4px;
    cursor: pointer;
    opacity: 0.5;
    background-color: #ff99cc;
    position: absolute;
}

And, finally, check the JavaScript (it’s all commented inside):

/**
iMouseDown represents the current mouse button state: up or down
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if (iMouseDown && !lMouseState) // button just clicked!
if (!iMouseDown && lMouseState) // button just released!
*/
var mouseOffset = null;
var iMouseDown = false;
var lMouseState = false;

// Demo 0 variables
var DragDrops = [];
var curTarget = null;
var lastTarget = null;
var rootParent = null;
var rootSibling = null;

Number.prototype.NaN0 = function () {
    "use strict";

    return isNaN(this) ? 0 : this;
};

function CreateDragContainer(element) {
    "use strict";

    /*
	Create a new "Container Instance" so that items from one "Set" can not
	be dragged into items from another "Set"
	*/
    var j = 0,
        cDrag = DragDrops.length;

    DragDrops[cDrag] = [];
    element.setAttribute("DropObj", cDrag);

    /*
	Each item passed to this function should be a "container".  Store each
	of these items in our current container
	*/
    DragDrops[cDrag].push(element);

    /*
    Every top level item in these containers should be draggable.  Do this
    by setting the DragObj attribute on each item and then later checking
    this attribute in the mouseMove function
    */
    for (j = 0; j < element.childNodes.length; j += 1) {
        // Firefox puts in lots of #text nodes...skip these
        if (element.childNodes[j].nodeName !== "#text") {
            element.childNodes[j].setAttribute("DragObj", cDrag);
        }
    }
}

function getPosition(e) {
    "use strict";

    var left = 0,
        top = 0;

    while (e.offsetParent) {
        left +=
            e.offsetLeft +
            (e.currentStyle
                ? parseInt(e.currentStyle.borderLeftWidth, 10).NaN0()
                : 0);
        top +=
            e.offsetTop +
            (e.currentStyle
                ? parseInt(e.currentStyle.borderTopWidth, 10).NaN0()
                : 0);
        e = e.offsetParent;
    }

    left +=
        e.offsetLeft +
        (e.currentStyle
            ? parseInt(e.currentStyle.borderLeftWidth, 10).NaN0()
            : 0);
    top +=
        e.offsetTop +
        (e.currentStyle
            ? parseInt(e.currentStyle.borderTopWidth, 10).NaN0()
            : 0);

    return { x: left, y: top };
}

function mouseCoords(ev) {
    "use strict";

    if (ev.pageX || ev.pageY) {
        return {
            x: ev.pageX,
            y: ev.pageY
        };
    }

    return {
        x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y: ev.clientY + document.body.scrollTop - document.body.clientTop
    };
}

function getMouseOffset(target, ev) {
    "use strict";

    ev = ev || window.event;

    var docPos = getPosition(target),
        mousePos = mouseCoords(ev);

    return {
        x: mousePos.x - docPos.x,
        y: mousePos.y - docPos.y
    };
}

function mouseMove(ev) {
    "use strict";

    ev = ev || window.event;

    /*
     * We are setting target to whatever item the mouse is currently on
     * Firefox uses event.target here, MSIE uses event.srcElement
     */
    var elementInstance,
        target = ev.target || ev.srcElement,
        mousePos = mouseCoords(ev),
        origClass,
        dragClass,
        dragConts,
        dragObj,
        oClass,
        pos,
        i,
        j;

    // mouseOut event - fires if the item the mouse is on has changed
    if (lastTarget && target !== lastTarget) {
        // reset the classname for the target element
        origClass = lastTarget.getAttribute("origClass");
        if (origClass) {
            lastTarget.className = origClass;
        }
    }

    /*
    dragObj is the grouping our item is in (set from the createDragContainer function).
    if the item is not in a grouping we ignore it since it can't be dragged with this
    script.
    */
    dragObj = target.getAttribute("DragObj");

    // if the mouse was moved over an element that is draggable
    if (dragObj !== null) {
        // if the user is just starting to drag the element
        if (iMouseDown && !lMouseState) {
            // mouseDown target
            curTarget = target;

            // Record the mouse x and y offset for the element
            rootParent = curTarget.parentNode;
            rootSibling = curTarget.nextSibling;

            mouseOffset = getMouseOffset(target, ev);

            /*
			Record the current position of all drag/drop targets related
			to the element.  We do this here so that we do not have to do
			it on the general mouse move event which fires when the mouse
			moves even 1 pixel.  If we don't do this here the script
			would run much slower.
			*/
            dragConts = DragDrops[dragObj];

            /*
			first record the width/height of our drag item.  Then hide it since
			it is going to (potentially) be moved out of its parent.
			*/
            curTarget.setAttribute(
                "startWidth",
                parseInt(curTarget.offsetWidth, 10)
            );
            curTarget.setAttribute(
                "startHeight",
                parseInt(curTarget.offsetHeight, 10)
            );
            curTarget.style.display = "none";

            // loop through each possible drop container
            for (i = 0; i < dragConts.length; i += 1) {
                elementInstance = dragConts[i];

                pos = getPosition(dragConts[i]);

                /*
				save the width, height and position of each container.

                Even though we are saving the width and height of each
				container back to the container this is much faster because
				we are saving the number and do not have to run through
				any calculations again.  Also, offsetHeight and offsetWidth
				are both fairly slow.  You would never normally notice any
				performance hit from these two functions but our code is
				going to be running hundreds of times each second so every
				little bit helps!

				Note that the biggest performance gain here, by far, comes
				from not having to run through the getPosition function
				hundreds of times.
				*/
                elementInstance.setAttribute(
                    "startWidth",
                    parseInt(elementInstance.offsetWidth, 10)
                );
                elementInstance.setAttribute(
                    "startHeight",
                    parseInt(elementInstance.offsetHeight, 10)
                );
                elementInstance.setAttribute("startLeft", pos.x);
                elementInstance.setAttribute("startTop", pos.y);

                // Loop through each child element of each container
                for (j = 0; j < dragConts[i].childNodes.length; j += 1) {
                    elementInstance = dragConts[i].childNodes[j];

                    if (
                        elementInstance.nodeName === "#text" ||
                        dragConts[i].childNodes[j] === curTarget
                    ) {
                        continue;
                    }

                    pos = getPosition(dragConts[i].childNodes[j]);

                    // Save the width, height and position of each element
                    elementInstance.setAttribute(
                        "startWidth",
                        parseInt(elementInstance.offsetWidth, 10)
                    );
                    elementInstance.setAttribute(
                        "startHeight",
                        parseInt(elementInstance.offsetHeight, 10)
                    );
                    elementInstance.setAttribute("startLeft", pos.x);
                    elementInstance.setAttribute("startTop", pos.y);
                }
            }
        }
    }

    // If we get in here we are dragging something
    if (curTarget) {
        dragConts = DragDrops[curTarget.getAttribute("DragObj")];
        var activeCont = null;

        var xPos =
            mousePos.x -
            mouseOffset.x +
            parseInt(curTarget.getAttribute("startWidth"), 10) / 2;
        var yPos =
            mousePos.y -
            mouseOffset.y +
            parseInt(curTarget.getAttribute("startHeight"), 10) / 2;

        // check each drop container to see if our target object is "inside" the container
        for (i = 0; i < dragConts.length; i += 1) {
            elementInstance = dragConts[i];

            if (
                parseInt(elementInstance.getAttribute("startLeft"), 10) <
                    xPos &&
                parseInt(elementInstance.getAttribute("startTop"), 10) < yPos &&
                parseInt(elementInstance.getAttribute("startLeft"), 10) +
                    parseInt(elementInstance.getAttribute("startWidth"), 10) >
                    xPos &&
                parseInt(elementInstance.getAttribute("startTop"), 10) +
                    parseInt(elementInstance.getAttribute("startHeight"), 10) >
                    yPos
            ) {
                /*
                our target is inside of our container so save the container into
                the activeCont variable and then exit the loop since we no longer
                need to check the rest of the containers
                */
                activeCont = dragConts[i];

                // exit the for loop
                break;
            }
        }

        // Our target object is in one of our containers.  Check to see where our div belongs
        if (activeCont) {
            if (activeCont !== curTarget.parentNode) {
                //activeCont.id;
            }

            // beforeNode will hold the first node AFTER where our div belongs
            var beforeNode = null;

            // loop through each child node (skipping text nodes).
            for (i = activeCont.childNodes.length - 1; i >= 0; i -= 1) {
                elementInstance = activeCont.childNodes[i];

                if (elementInstance.nodeName === "#text") {
                    continue;
                }

                // if the current item is "After" the item being dragged
                if (
                    curTarget != activeCont.childNodes[i] &&
                    parseInt(elementInstance.getAttribute("startLeft")) +
                        parseInt(elementInstance.getAttribute("startWidth")) >
                        xPos &&
                    parseInt(elementInstance.getAttribute("startTop")) +
                        parseInt(elementInstance.getAttribute("startHeight")) >
                        yPos
                ) {
                    beforeNode = activeCont.childNodes[i];
                }
            }

            // the item being dragged belongs before another item
            if (beforeNode) {
                if (beforeNode != curTarget.nextSibling) {
                    activeCont.insertBefore(curTarget, beforeNode);
                }

                // the item being dragged belongs at the end of the current container
            } else {
                if (
                    curTarget.nextSibling ||
                    curTarget.parentNode != activeCont
                ) {
                    activeCont.appendChild(curTarget);
                }
            }

            // the timeout is here because the container doesn't "immediately" resize
            setTimeout(function () {
                var contPos = getPosition(activeCont);
                activeCont.setAttribute(
                    "startWidth",
                    parseInt(activeCont.offsetWidth)
                );
                activeCont.setAttribute(
                    "startHeight",
                    parseInt(activeCont.offsetHeight)
                );
                activeCont.setAttribute("startLeft", contPos.x);
                activeCont.setAttribute("startTop", contPos.y);
            }, 5);

            // make our drag item visible
            if (curTarget.style.display !== "") {
                curTarget.style.display = "";
                curTarget.style.visibility = "visible";
                curTarget.classList.add('DragHelper');
            }
        }
    }

    // track the current mouse state so we can compare against it next time
    lMouseState = iMouseDown;

    // mouseMove target
    lastTarget = target;

    // track the current mouse state so we can compare against it next time
    lMouseState = iMouseDown;

    // this prevents items on the page from being highlighted while dragging
    if (curTarget) return false;
}

function mouseUp() {
    if (curTarget) {
        if (curTarget.style.display == "none") {
            if (rootSibling) {
                rootParent.insertBefore(curTarget, rootSibling);
            } else {
                rootParent.appendChild(curTarget);
            }
        }
        curTarget.style.display = "";
        curTarget.style.visibility = "visible";
                curTarget.classList.remove('DragHelper');
    }
    curTarget = null;
    iMouseDown = false;

    // action!
}

function mouseDown(ev) {
    ev = ev || window.event;

    var target = ev.target || ev.srcElement;

    iMouseDown = true;

    if (target.onmousedown || target.getAttribute("DragObj")) {
        return false;
    }
}

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup = mouseUp;

window.onload = function () {
    CreateDragContainer(document.querySelector(".DragContainer"));
};

Solution #4: DragonflyJS – Vanilla JavaScript Drag and Drop

Based on solution #3, I have created a library called DragonflyJS for easy installation and usage.

By implementing this library, a user is able to drag and drop elements and reorder them. This library enables a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items are draggable.

Related posts