Creating a Sortable List Items using JavaScript Tutorial

In this tutorial, you can learn how to Create a Sortable List of Items using JavaScript. The tutorial aims to provide students and new programmers with a reference for learning to build a useful component for a website or web application. Here, I will be providing a simple web application's web page that demonstrates the creation of simple Sortable List Items.

What is Sortable List?

The Sortable List is a simple and useful component or feature of a website and web applications. It can be used for displaying list elements in vertical or horizontal order. This allows the end-user to sort the order of the list items by dragging the item to the new location or position.

How to Create a Sortable List?

Using JavaScript we can simply create a sorting or drag-and-drop functionality for the HTML list element items. JS comes with some useful event listeners to achieve this kind of component such as the dragstart and dragend events. Check out the source code scripts I provided below to understand more and have an actual Idea of how to build a simple sortable list using JavaScript.

Sample Web Application

The scripts below output a simple web application's web page that contains a list of notes with order or sorting functionality.

Interface

The following script is an HTML code that contains the static content of the web page and a list of items. Save the file script as index.html.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JS - Sortable List Items</title>
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  10. <link rel="stylesheet" href="style.css">
  11. </head>
  12. <main>
  13. <h1 class="text-center page-title"><b>Sortable List Items</b></h1>
  14. <hr width="50px">
  15. <div class="sortable-list-container">
  16. <ul>
  17. <li draggable="true">
  18. <div class="flex-container">
  19. <div>
  20. <span class="material-symbols-outlined">
  21. drag_indicator
  22. </span>
  23. </div>
  24. <div>Sample Note #1</div>
  25. </div>
  26. </li>
  27. <li draggable="true">
  28. <div class="flex-container">
  29. <div>
  30. <span class="material-symbols-outlined">
  31. drag_indicator
  32. </span>
  33. </div>
  34. <div>Sample Note #2</div>
  35. </div>
  36. </li>
  37. <li draggable="true">
  38. <div class="flex-container">
  39. <div>
  40. <span class="material-symbols-outlined">
  41. drag_indicator
  42. </span>
  43. </div>
  44. <div>Sample Note #3</div>
  45. </div>
  46. </li>
  47. <li draggable="true">
  48. <div class="flex-container">
  49. <div>
  50. <span class="material-symbols-outlined">
  51. drag_indicator
  52. </span>
  53. </div>
  54. <div>Sample Note #4</div>
  55. </div>
  56. </li>
  57. <li draggable="true">
  58. <div class="flex-container">
  59. <div>
  60. <span class="material-symbols-outlined">
  61. drag_indicator
  62. </span>
  63. </div>
  64. <div>Sample Note #5</div>
  65. </div>
  66. </li>
  67. </ul>
  68. </div>
  69. </main>
  70. <script src="script.js"></script>
  71. </body>
  72. </html>

Stylesheet

Next, I created the following CSS script or stylesheet for the design of the web page and list items. Save the file as style.css. Make sure to load this file on the index page.

  1. @import url('https://fonts.googleapis.com/css2?family=Rubik&display=swap');
  2. body *{
  3. font-family: 'Rubik', sans-serif;
  4. }
  5. /**
  6. Page Design
  7. */
  8. body,
  9. html{
  10. height: 100%;
  11. width: 100%;
  12. margin: 0;
  13. padding: 0;
  14. }
  15. body{
  16. background-color: #B9F3E4;
  17. }
  18. main{
  19. padding: 3em 15em;
  20. }
  21. section{
  22. width:100%;
  23. }
  24. .text-center{
  25. text-align: center;
  26. }
  27. .page-title{
  28. color: #fff;
  29. text-shadow: 1px 1px 3px #000;
  30. }
  31. .flex-container{
  32. display: flex;
  33. width: 100%;
  34. flex-wrap: wrap;
  35. align-items: center;
  36. }
  37.  
  38. .sortable-list-container{
  39. width: 400px;
  40. background-color: #fff;
  41. border: 1px solid #dedede;
  42. box-shadow:1px 1px 5px #6c6c6c;
  43. margin: auto ;
  44. }
  45. .sortable-list-container ul{
  46. padding: .5em 1em;
  47. }
  48. .sortable-list-container ul li{
  49. list-style: none ;
  50. border: 1px solid #cfcfcf;
  51. box-shadow:1px 1px 5px #a8a8a8;
  52. margin-bottom: 10px;
  53. padding: 0.5em 1em;
  54. cursor: grab;
  55. background: #fff;
  56. }
  57. .sortable-list-container ul li[data-dragging="true"]{
  58. border-style: dashed;
  59. box-shadow: unset;
  60. }
  61. .sortable-list-container ul li[data-dragging="true"] :where(*){
  62. opacity: 0;
  63. }
  64.  

Sorting Script

Finally, here's the JavaScript file script that contains the codes that make our sortable list functional. The script contains some comments to understand more. Save this file as script.js and make sure to load this on the index page too.

  1. /** Selcect Sortable List Container */
  2. const sortableList = document.querySelectorAll(".sortable-list-container ul")
  3.  
  4. /** Sorting Function */
  5. const initSortableList = (e, listGroup) => {
  6. e.preventDefault()
  7. //List all list items of the list group
  8. var listItems = listGroup.querySelectorAll("li")
  9.  
  10. // Current Item to transfer
  11. var currentDragging = listGroup.querySelector('li[data-dragging="true"]')
  12.  
  13. // where mouse is pointing
  14. var currentPosition = e.clientY
  15. listItems.forEach(listItem=>{
  16. var rangeFrom = listItem.offsetTop;
  17. var rangeto = listItem.offsetTop + (listItem.clientHeight / 2);
  18. var rangeto2 = listItem.offsetTop + listItem.clientHeight;
  19.  
  20. if(currentPosition > rangeFrom && currentPosition < rangeto){
  21. // Insert/Transfer Item before the Item if the mouse cursor is pointing at the upper area
  22. listGroup.insertBefore(currentDragging, listItem)
  23. }else if(currentPosition > rangeFrom && currentPosition < rangeto2){
  24. // Insert/Transfer Item after the Item if the mouse cursor is pointing at the lower area
  25. listItem.after(currentDragging)
  26. }
  27. })
  28. }
  29. sortableList.forEach(listGroup => {
  30. //Select All Draggable Enabled list items of the list group
  31. var listItems = listGroup.querySelectorAll("li[draggable='true']")
  32.  
  33. listItems.forEach(listItem=>{
  34. /** Event when drag started */
  35. listItem.addEventListener('dragstart', function(e){
  36. e.dataTransfer.effectAllowed = "move";
  37. setTimeout(()=>{
  38. listItem.dataset.dragging = "true"
  39. }, 10)
  40.  
  41. })
  42. listItem.addEventListener('dragend', function(e){
  43. listItem.dataset.dragging = "false"
  44. })
  45. })
  46. listGroup.addEventListener('dragover', (e)=>{
  47. /** Initializing Sort */
  48. initSortableList(e, listGroup)
  49. })
  50. })
  51.  

There you go! The following snapshots or images are the output of the web application's scripts that I provided above.

Snapshots

Default Sorting of Items

Sortable List using JS

When dragging the Items to the new location

Sortable List using JS

When Items are Re-ordered or Sorted

Sortable List using JS

DEMO VIDEO

That's it! You can also download the complete source code zip file of the script I have provided on this site. To download it, click the download button located below this tutorial's content.

That's the end of this tutorial! I hope this Creating a Sortable List Items using JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.

Happy Coding =)

Add new comment