views:

1002

answers:

3

I am wondering the "how it works" and "how it should be designed and implemented" side of the basic drag & drop functionality.

I have never yet implemented such a functionality. I am planning to do so for one of my projects and I do have some ideas on how to implement it. I wanted to make sure I am on the right path and that you people most probably has something to say about the matter too...

Let's imagine I have 5 elements listed as following and grabbed from a database;

<div id="1">this is content for 1</div>
<div id="2">this is content for 2</div>
<div id="3">this is content for 3</div>
<div id="4">this is content for 4</div>
<div id="5">this is content for 5</div>

since this is pulled off from a database we know that it has a field called "sequence" or "order" to distinguish the order we are going to output. Let's also imagine currently the "sequence" column values are the same as the IDs of the divs. so: 1,2,3,4 and 5 respectively.

My question and thoughts;

If I drag div 4 and drop it between 1 and 2; what are the steps from there on? E.g:

1) determine the id of the div that is being dragged (let's call this div-a)

2) determine the id of the div that div-a is being inserted after (or before) in this case after and therefore after div id 1 (let's call this div-b)

3) Update div-a's sequence in db and set it to the current sequence of div-b

after this step I am all confused... Do I count all the divs and according to which ever order the divs are, do I update the db accordingly? or am I completely wrong and is there another way?


thanks for the answers but I know there are plugins and other stuff to get this done but I am only interested in the logic part of it..

+1  A: 

I believe jquery gives you a way to grab their order based on id?

The way I've been doing it is every time an action occurs, grab the current order, send it back to my app via ajax. Then my app just parses out the ids from what it was given and updates every item's order value.

phillc
thanks phillic for your answer. I was interested in the logic not the code on how to do it... your response gave me an idea and proved I was in the right path.
Emin
A: 

Unless you are doing this for your own education, I would suggest that you use jQueryUI.

It has drag-and-drop functionality, amongst other things, that would probably help you with the nitty-gritty of DaD, leaving you to implement the parts that are specific to your problem.

Julian
+1  A: 

http://jqueryui.com/demos/sortable/

    $("#col1").sortable({
        placeholder: "top",
        forcePlaceholderSize: true,
        revert: true, 
        update: function() { 
                $.ajax({
                  type: "GET",
                  url: "/request.php",
                  data: "data="+$(this).sortable("toArray")+"",
                  success: function(msg){ }
                        });   
             }
    });

toArray is a sequence of your divs ids

zalew