Reputation: 4079
I'm working on building a new website purely for learning purposes and I want to try and implement some drag/drop sorting system. I am aware that jQuery provide the sortable UI component http://jqueryui.com/sortable/ but I want to have a go at designing and building the system from scratch (seen as this is for learning purposes).
When it comes to Javascript I have to admit I am fairly novice, so I was wondering if any of you could offer your 2 cents against my current thinking of how the program would work:
Questions:
1) My main problem with this is, how do I detect when I have passed another li element when dragging? I could assume width n has been passed, but each cell could be of variable length making that solution inappropriate.
2) I am also assuming I am going to need to use AJAX to handle the callback, otherwise I am going to get some undesired page refreshes (right)?
Hopefully this won't receive down votes - I want to stress that I am NOT seeking a solution from you guys, I have used these forums long enough to know that I don't demand code from the community without providing any of my own work! I'd just like some feedback on my initial draft as well as answers to the 2 questions asked above.
Thanks in advance for your time
Alex.
Upvotes: 0
Views: 394
Reputation: 878
If you are using JQuery you can avoid having to know what order your items are in.
The .index() function will return the position of the item relative to its siblings.
You can then simply keep track of the element you want to move by adding a working class to it on a mouse down even. (I use .draging in my example)
On the mouseup event just find our old item by the class you added. Depending on which element is first compared to the other, insert your working element before or after the element you mousedup on and then remove your working class.
Here is an example http://jsfiddle.net/V72Le/2/
function swap(dragable, draging) {
//find direction of move then move item based on direction
var from = $(dragable).index();
var to = $(draging).index();
if (from > -1 && to > -1) {
var direction = from - to;
if (direction > 0) {
$(draging).insertAfter($(dragable));
} else if (direction < 0) {
$(draging).insertBefore($(dragable));
}
}
}
Upvotes: 1