Musings

jQuery Sortable Lists With Drag Drop Handle

24th April 2008

jQuery Sortable Lists With Drag Drop Handle

this post has been extended in the new Extending the jQuery Sortable With Ajax & MYSQL post

I’ve recently made use of a drag / drop style list that will remember the order of the list. If you use the standard jQuery sortable items, you’ll get the two following problems:

  1. You won’t be able to click on any items in the sortable list you have
  2. You’ll probably want an update of the order of the list after every change.

I did find a solution to the problem over at Scott Sauyet’s site, but I needed a little more… The following example will do both, it uses the handle and update options on the .sortable item. By adding these simple items you can produce a pretty advanced sortable list. You could even add AJAX into that update command and automatically update your database with the new values every time you change then removing the need to refresh, and that’s very web 2.0.

DEMO AND SOURCE HAVE MOVED TO THE NEW POST

I’ve ‘enhanced’ it ever so slightly by adding in some styles for the list items and handles.

First we’ll look at the CSS:

<style> 
  #test-list { list-style: none; padding: 0; margin: 0 40px; } 
  #test-list li { margin: 0 0 10px 0; background: #eaf3fa; padding: 15px; } 
  #test-list .handle { float: left; margin-right: 10px; cursor: move; } 
  #test-log { padding: 5px; border: 1px solid #ccc; } 
</style>

Then we need to include jQuery and the jQuery UI

<script type="text/javascript" src="{ latest jquery release }"></script> 
<script type="text/javascript" src="{ ui core }"></script> 
<script type="text/javascript" src="{ ui sortable }"></script> 

We then tell the document to automatically handle the list when it’s ready

<script type="text/javascript">// When the document is ready set up our sortable with it's inherant function(s) 
$(document).ready(function() { 
  $("#test-list").sortable({ 
    handle : '.handle', 
    update : function () { 
      $("input#test-log").val($('#test-list').sortable('serialize')); 
    } 
  }); 
}); 
</script>

Now to build the HTML:

<ul id="test-list"> 
    <li id="listItem_1"> 
    <img src="arrows.png" class="handle" alt="move" /> 
      Item 1 with a link to <a href="http://www.google.co.uk/" rel="nofollow">Google</a> 
    </li> 
    <li id="listItem_2"> 
      <img src="arrow.png" class="handle" alt="move" /> 
      Item 2 
    </li> 
    <li id="listItem_3"> 
      <img src="arrow.png" class="handle" alt="move" /> 
      Item 3 
    </li> 
    <li id="listItem_4"> 
      <img src="arrow.png" class="handle" alt="move" /> 
      Item 4 
      <p>Perhaps you want to add a form in here?</p> 
      <p>Text:<br /><input type="text" /></p> 
      <p>And a textarea<br /><textarea></textarea></p> 
    </li> 
</ul> 
<label for="test-log"><strong>Resultant order of list</strong></label> 
<input type="text" size="70" id="test-log" />

One important thing to remember, that might have you stumbling is that you HAVE to name the list items as such id=“item_1” that underscore and number will define the elements in the array past out to the text box.

Experiment, enjoy.

Discuss

Get involved in the discussion by using the comment form below.

omg

25th July 2008

thx

omg

25th July 2008

thx

david

30th July 2008

thank you very much

david

30th July 2008

thank you very much

andol

31st July 2008

i d like to know if this dragable div could be droped in any place on the page, and keep this positon data to database?
thanks for your share, i really like it.

andol

31st July 2008

i d like to know if this dragable div could be droped in any place on the page, and keep this positon data to database?
thanks for your share, i really like it.

wil.linssen

31st July 2008

andol - if by the draggable div you mean the handle then you could use css to move it most anywhere, you need to have something with the class name .handle to act as the dragging mechanism. If you give the list item a relative position you could then easily use an absolute one for the handle to drop it 100px to the right or something, hopefully that’s what you meant.

wil.linssen

31st July 2008

andol - if by the draggable div you mean the handle then you could use css to move it most anywhere, you need to have something with the class name .handle to act as the dragging mechanism. If you give the list item a relative position you could then easily use an absolute one for the handle to drop it 100px to the right or something, hopefully that’s what you meant.

DP

18th August 2008

Is there any way to drag a paragraph of text into a textarea (in a form)?

For example, the textarea contains Paragraph 1, 2 & 3, but you want to drop an extra paragraph between 2 & 3 (but keeping everything inside the textarea).

DP

18th August 2008

Is there any way to drag a paragraph of text into a textarea (in a form)?

For example, the textarea contains Paragraph 1, 2 & 3, but you want to drop an extra paragraph between 2 & 3 (but keeping everything inside the textarea).

wil.linssen

19th August 2008

I’d suggest you have all your paragraphs as list items which can be re-ordered with the above code. When you click submit, the order of the paragraphs is recorded and the text restructured accordingly.

You could add new paragraphs to the list using Ajax and the jQuery Form plugin too? If I’ve misunderstood your question, just elaborate with exactly what you need to perform.

wil.linssen

19th August 2008

I’d suggest you have all your paragraphs as list items which can be re-ordered with the above code. When you click submit, the order of the paragraphs is recorded and the text restructured accordingly.

You could add new paragraphs to the list using Ajax and the jQuery Form plugin too? If I’ve misunderstood your question, just elaborate with exactly what you need to perform.

ismail

25th August 2008

i need a drag chart with jquery but the dragged item should stay at its old place also.

ismail

25th August 2008

i need a drag chart with jquery but the dragged item should stay at its old place also.

wil.linssen

25th August 2008

ismail: you want to copy the whole chart to a new location when you drag it, or just elements in the chart? What type of chart is it?

wil.linssen

25th August 2008

ismail: you want to copy the whole chart to a new location when you drag it, or just elements in the chart? What type of chart is it?

Rico

27th August 2008

great work, thank you!

Rico

27th August 2008

great work, thank you!

andy

2nd September 2008

Thanks for this - just what I have been looking for as my jQuery (and javascript generally) is still at the ‘infant’ stage!
I am hoping you may be able to advise though… I am wanting to use this for a group of small images (re-ordering icons actually) and would very much prefer to display then horizontally. Using a ‘display: inline’ works visually but then the drag and drop is inconsistent, sometimes working, sometimes not - does not always open up for the drop etc.
Do you know of a way I might achieve this?
The code is very much appreciated and thanks again.

andy

2nd September 2008

Thanks for this - just what I have been looking for as my jQuery (and javascript generally) is still at the ‘infant’ stage!
I am hoping you may be able to advise though… I am wanting to use this for a group of small images (re-ordering icons actually) and would very much prefer to display then horizontally. Using a ‘display: inline’ works visually but then the drag and drop is inconsistent, sometimes working, sometimes not - does not always open up for the drop etc.
Do you know of a way I might achieve this?
The code is very much appreciated and thanks again.

andy

2nd September 2008

Stupid! My mistake! Got it now. Thanks again - this is perfect…

andy

2nd September 2008

Stupid! My mistake! Got it now. Thanks again - this is perfect…

wil.linssen

2nd September 2008

@andy sometimes you just need someone to tell the problem and the solution appears to you! Glad you sorted it, good luck with the rest of it.

wil.linssen

2nd September 2008

@andy sometimes you just need someone to tell the problem and the solution appears to you! Glad you sorted it, good luck with the rest of it.

Lionel

3rd September 2008

Hi,

Thanks for sharing
can we use persistence?
Can you point me to where I could grab myself an ajax script to insert the array in a databse?

Lionel

3rd September 2008

Hi,

Thanks for sharing
can we use persistence?
Can you point me to where I could grab myself an ajax script to insert the array in a databse?

wil.linssen

11th September 2008

@Lionel You’ll probably want to create another PHP file that will receive, handle and return your variables from the jQuery.

Add a function into the update part to do just that, and there is plenty on that in the jQuery docs. Alternatively you could just Google jQuery AJAX POST (or GET.)

wil.linssen

11th September 2008

@Lionel You’ll probably want to create another PHP file that will receive, handle and return your variables from the jQuery.

Add a function into the update part to do just that, and there is plenty on that in the jQuery docs. Alternatively you could just Google jQuery AJAX POST (or GET.)

soulcrazy

21st September 2008

Can I use a helperclass:

helperclass: ‘sort_placeholder’,

to change backgorund of ‘target drop-areas’ when comes close? Doesn’t seem to work on my end.

soulcrazy

21st September 2008

Can I use a helperclass:

helperclass: ‘sort_placeholder’,

to change backgorund of ‘target drop-areas’ when comes close? Doesn’t seem to work on my end.

soulcrazy

21st September 2008

Ah! Thank you for this code. I managed to implement additional effects into this for an amazing result.

Email me if you would like the source. I’d be happy to share.

soulcrazy

21st September 2008

Ah! Thank you for this code. I managed to implement additional effects into this for an amazing result.

Email me if you would like the source. I’d be happy to share.

Volo Mike

24th November 2008

Wil - got an example that uses stacked DIVs instead of LI’s? I’m needing to make an interface to let one resort their resume items, so I was going to make a kind of graphical representation of each section and let them drag the sections around. Shoot me an email if you get a chance?

Volo Mike

24th November 2008

Wil - got an example that uses stacked DIVs instead of LI’s? I’m needing to make an interface to let one resort their resume items, so I was going to make a kind of graphical representation of each section and let them drag the sections around. Shoot me an email if you get a chance?

James

8th December 2008

Thanks for the guidance! Great article.

James

8th December 2008

Thanks for the guidance! Great article.

Deepak

8th December 2008

After sorting the data.
If we would like to save it .then how to do it.

ex:1,2,3,4,5 (before sorted)

(after sorting)2,4,1,5,3
(So how to save it )

Deepak

8th December 2008

After sorting the data.
If we would like to save it .then how to do it.

ex:1,2,3,4,5 (before sorted)

(after sorting)2,4,1,5,3
(So how to save it )

Bookmarks about Jquery

11th December 2008

[...] - bookmarked by 4 members originally found by pdorl on 2008-11-02 jQuery Sortable Lists With Drag Drop Handle http://www.wil-linssen.com/jquery-sortable-lists-with-drag-drop-handle/ - bookmarked by 1 members [...]

Bookmarks about Jquery

11th December 2008

[...] - bookmarked by 4 members originally found by pdorl on 2008-11-02 jQuery Sortable Lists With Drag Drop Handle http://www.wil-linssen.com/jquery-sortable-lists-with-drag-drop-handle/ - bookmarked by 1 members [...]

wil.linssen

11th December 2008

@Deepak: in this example it’s adding the order to an input box, you could submit that input box and deal with it on another page.

The page dealing with the box would receive the values in an array called listItem, so $_POST[‘listItem’][0] would be the first item and so on.

You could acheive the same result by calling an AJAX script to the same page hence removing the need to refresh / navigate away.

wil.linssen

11th December 2008

@Deepak: in this example it’s adding the order to an input box, you could submit that input box and deal with it on another page.

The page dealing with the box would receive the values in an array called listItem, so $_POST[‘listItem’][0] would be the first item and so on.

You could acheive the same result by calling an AJAX script to the same page hence removing the need to refresh / navigate away.

JR Chew

12th December 2008

Nice man, very nice! I think i’ll add the ajax database update code.

JR Chew

12th December 2008

Nice man, very nice! I think i’ll add the ajax database update code.

rvturnage

3rd January 2009

Very nice code…I’m a bit of a beginner to this, and have the sort working right off the bat!

I wonder, though, could someone walk me through implementing the code to update a mysql database using the AJAX update code I’ve seen mentioned?

Thanks again for this wonderful tutorial!
rvt

rvturnage

3rd January 2009

Very nice code…I’m a bit of a beginner to this, and have the sort working right off the bat!

I wonder, though, could someone walk me through implementing the code to update a mysql database using the AJAX update code I’ve seen mentioned?

Thanks again for this wonderful tutorial!
rvt

wil.linssen

3rd January 2009

@rvturnage I’ve been meaning to write an update for this piece for a while, and you inspired me to finally do it. I’ve now added a new post showing how to update the list AND then parse the results with PHP and AJAX. This means you could happily add the results to your database without refreshing the page.

wil.linssen

3rd January 2009

@rvturnage I’ve been meaning to write an update for this piece for a while, and you inspired me to finally do it. I’ve now added a new post showing how to update the list AND then parse the results with PHP and AJAX. This means you could happily add the results to your database without refreshing the page.

rvturnage

4th January 2009

LOL! Thanks, Wil. Glad I could inspire you. I actually figured it out after re-reading a link you provided to someone else earlier and was about to post it when I saw your reply! I really appreciate your work!

rvt

rvturnage

4th January 2009

LOL! Thanks, Wil. Glad I could inspire you. I actually figured it out after re-reading a link you provided to someone else earlier and was about to post it when I saw your reply! I really appreciate your work!

rvt

Igor

26th January 2009

Greetings, i was very amused by this example.
I am thinking on using it but i need to make several ordered lists in the same page, since i ahve to define the items this way : “HAVE to name the list items as such id=”item_1?” is it possible? thanks

Igor

26th January 2009

Greetings, i was very amused by this example.
I am thinking on using it but i need to make several ordered lists in the same page, since i ahve to define the items this way : “HAVE to name the list items as such id=”item_1?” is it possible? thanks

geoid

13th July 2009

Love the look of your site…

geoid

13th July 2009

Love the look of your site…

Muthu

27th July 2009

I need to add a “Move to Top” button, is there a
way to trigger Sortable programmatically? Thanks in advance.

B

12th September 2009

Thank you sir. Rest assured that you inadvertently helped build the greatest web app ever. kudos!

wil.linssen

12th September 2009

@B best comment ever.

Anil Dutt

22nd April 2010

Its not working properly in IE when there are multiple lists, i mena if we have ul under li, then sorting not working in IE, working fine in FF, any suggestion

MindOverTEch

22nd April 2010

Your site theme is excelent.

I m considering using this plug in for my website but it seems to have some limitations in working properly with diferent browsers when we have more “complex” stuff.

Will you be updating it or making new versions?

thanks

Wil Linssen

22nd April 2010

@Anil & @MindOverTEch I’d love to update this post - it’s massively out of date, I just need to find the time really.

Theodore

13th June 2010

does this work with the original draggable (connectWithSortable)?

Jonny

17th June 2010

Just wanted to thank you for posting this. I had no previous experience with JQuery and was able to successfully incorporate your code into a .NET project I’m working on. Worked perfectly!

George

20th June 2010

Very nice script. But it doesn’t work on a iPad

Wil Linssen

20th June 2010

I think I’ll close out the comments on this one now, the tutorial was originally posted in 2006, and I reckon by now we’ve moved on a bit as George’s powerfully astute comment might suggest. If I get some time soon I’ll post up how I’d do it all in 2010.

Commenting is not available in this section entry.

Copyright © 2009 Wil Linssen all rights reserved

Wil-Linssen.com is powered by ExpressionEngine: it's good, go and get it.