Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

James Barrett
James Barrett
13,253 Points

HTML5 Drag and & Drop - Moving Elements Within a List

I am trying out HTML5 Drag and Drop Web API and trying to incorporate it into a simple To-Do App project. I have partially implemented my intended functionality, whereby I swap around the dragged list item with the list item where it is dropped.

However, I have a bug at the moment where if the user drags a list item into any <span> or a <button>, it places the dragged data as a child of these elements?

HTML:

<ul id="list-items">
    <li draggable="true" ondragstart="dragStarted(event)" ondragover="draggingOver(event)" ondrop="dropped(event)">
        <span>Jack</span>
        <button>Edit</button>
        <button>Remove</button>
    </li>
    <li draggable="true" ondragstart="dragStarted(event)" ondragover="draggingOver(event)" ondrop="dropped(event)">
        <span>Josh</span>
        <button>Edit</button>
        <button>Remove</button>
    </li>
</ul>

JavaScript:

let source;

function dragStarted(e) {
source = e.target;
  e.dataTransfer.setData("text/plain", e.target.innerHTML);
  e.dataTransfer.effectAllowed = "move";
}

function draggingOver(e) {
  e.preventDefault();
  e.dataTransfer.dropEffect = "move";
}

function dropped(e) {
  e.preventDefault();
  e.stopPropagation();
  source.innerHTML = e.target.innerHTML;
  e.target.innerHTML = e.dataTransfer.getData("text/plain");
}

Why is this happening and how can I fix this?

View full codepen here: https://codepen.io/jamesbarrett95/pen/LWqQoB

Thanks, James.

1 Answer

Rune Andreas Nielsen
Rune Andreas Nielsen
5,354 Points

Hi, James.

A simple way to prevent it is by using a conditional on the 'dropped' function to check if the element is a list. Next step to make your solution better would be to find the closest 'li' element if the user tries to drop it on the button or span and move the dragged element into the closest list.

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

    if (e.target.localName === 'li') {
        source.innerHTML = e.target.innerHTML;
        e.target.innerHTML = e.dataTransfer.getData("text/plain");
    }
}

Good luck :)

James Barrett
James Barrett
13,253 Points

Thanks! Very simple way to fix it