0

I want to allow drag and drop in an html unordered list. The solution I've found is described here: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop2

But it seems I need to give an id to each element of my list (li), is it possible to do a drag and drop without using the id?

Also in this solution it seems that I can drag a li inside another one, how can I prevent this?

Here's a sample of what I have now (the javascript):

function drag(ev) {
    ev.dataTransfer.setData("Text",ev.target.id);
}

function allowDrop(ev) {
    ev.preventDefault();
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

[EDIT] Here is the html ul:

<ul id="members-list" ondragover="allowDrop(event)" 
    ondrop="drop(event)">
  <li id="drag1" class="group-member" 
      ondragstart="drag(event)" 
      draggable="true">
      <a href="">
        <img class="member-photo" 
             src="images/a.jpg" 
             alt="Bernardo Figueiredo"/>
        <div class="member-info">
          <p>bla</p>
          <p>blabla</p>
        </div>
      </a>
  </li>
  <!-- Other li -->
</ul>
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Luis Alves
  • 1,286
  • 12
  • 32

1 Answers1

3

You could use a global variable, save it to that variable in drag(), then access it in drop()

var elem;

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
    elem = ev.target;
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(elem);
}    

Demo

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
  • Thanks! By the way how can I prevent the drag and drop inside of the others li of the list? – Luis Alves Feb 19 '14 at 22:53
  • @LuisAlves Remove the `ondrop` event from the tag. [**Demo**](http://jsfiddle.net/Zeaklous/p3k2A/1/) – Zach Saucier Feb 19 '14 at 22:54
  • Yes but I only have the ondrop event on the ul tag. (I re-edit my post with the html part) – Luis Alves Feb 19 '14 at 22:55
  • @LuisAlves How many areas will be able to be dropped to? How are those areas determined? – Zach Saucier Feb 19 '14 at 23:01
  • I think this is not really going to do what I want. I have a list and I want to be able to change the order of the elements just by dragging and drop them. Is it really needed to set this areas? – Luis Alves Feb 19 '14 at 23:03
  • @LuisAlves For list reordering the most common solution is to use jQuery Sortable. If you're looking for a non-jQuery version, I cannot seem to find a good one. You could build your own based on other's examples, but that's for another SO question – Zach Saucier Feb 19 '14 at 23:14