Sorting elements with SortableJS and storing them in localStorage

by Janeth Kent Date: 15-05-2023 javascript

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change their position.

To learn what SortableJS is and how to get started, you can read the following tutorial.

In this article you are going to discover how to drag and drop elements to position them in another place and that the new positions of the elements are registered in localStorage for a next session.

The localStorage object allows you to store data locally in the user's browser without having to make a connection to a database.

 

List of elements to sort

 

In the running example I'm using a list of Bootstrap cards to give each element a nice, quick and different look.

In the body of the page or inside the <body> you can include the HTML code of the elements I'm going to sort:


<div class='row sortable'>
    <div class='col-lg-3' data-id=Ƈ'>
        <div class='card text-white bg-primary mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Primary card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div>
    <div class='col-lg-3' data-id=ƈ'>
        <div class='card text-white bg-secondary mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Secondary card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div>
    <div class='col-lg-3' data-id=Ɖ'>
        <div class='card text-white bg-success mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Success card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div>
    <div class='col-lg-3' data-id=Ɗ'>
        <div class='card text-white bg-danger mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Danger card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div>
    <div class='col-lg-3'  data-id=Ƌ'>
        <div class='card text-white bg-warning mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Warning card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div>
    <div class='col-lg-3' data-id=ƌ'>
        <div class='card text-white bg-info mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Info card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div>
    <div class='col-lg-3' data-id=ƍ'>
        <div class='card bg-light mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Light card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div>
    <div class='col-lg-3' data-id=Ǝ'>
        <div class='card text-white bg-dark mb-3' style='max-width: 18rem;'>
            <div class='card-header'>Header</div>
            <div class='card-body'>
                <h5 class='card-title'>Dark card title</h5>
                <p class='card-text'>Some quick example text to build on the card title and make up the bulk of the cards content.</p>
            </div>
        </div>
    </div> 
</div>

Pay special attention to the fact that each element or card has an identifier or data-id attribute that will be used to store it in a sorted list in localStorage.

 

SortableJS object inclusion

 

Before the closing tag of the <body> you can add the script:

<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

We are going to use a CDN to go fast although you can go to the official SortableJS site

 

Creating the SortableJS object

 

Next, also before the closing tag of the <body> but after the inclusion of the SortableJS class you must create the instance of the object you are going to work with.

See below:

 
<script>  
   var items = document.querySelector('.sortable');  Sortable.create(items, {      
   animation: 150,      
    chosenClass: "selected",      
    ghostClass: "ghost",      
    dragClass: "drag",      
     onEnd: () => {          
        console.log('an element was inserted');      
     },      
     group: "cards",      
     store: {          
        set:(sortable) => {              
        const orden = sortable.toArray();              
        localStorage.setItem(sortable.options.group.name, orden.join('|'));          
        },          
      //get list order       
      get: (sortable) => {              
      const orden = localStorage.getItem(sortable.options.group.name);              
      return orden ? orden.split('|') : [];          
       }      
       }  
      });  
</script>
 

With querySelector I select the container that contains the elements that will have this behaviour and then I pass the element as the first parameter of the Sortable.create() function.

In the second parameter of this function you can define the options.

In the case of the example:

. I define an animation setting a duration of 150ms.
- I set the class "chosen" to customise by means of CSS how the selected element will look like.
- I declare the class "ghost" to customise through CSS the ghost element.
- I define the class "drag" to customise through CSS the dragged element.
I use the onEnd() function to display a message in the console.

 

SortableJS parameters to save to localStorage

 

Defining the SortableJS group is key to be able to save it. In the case of the example, I have named it "cards".

SortableJS has a Store object that allows you to save the state of sortable items.

I use the set() function to get the array of items or cards and store it in localStorage with setItem().

This setItem() function has 2 parameters:

- The name of the array of items. In this case, it would be the same to put "cards".
- String with the identifiers of the elements separated by the symbol "|".

To retrieve the order of the list, the get() function of the Store object can be used, passing the sortable object as an argument.

With the function getItem() of localStorage I retrieve the list of ordered items and return it as an array.

 

Conclusions

 

As you can see it is quite easy and quick to save the sorted list items in localStorage.

Saving information in localStorage can be very useful when you need to save small pieces of user information to keep them active while browsing the website.

Saving the order of a list with JavaScript can be very useful.

However, maybe you are more used to store the records in the database.

Soon I'll publish a new post for you to see what it would be like to save SortableJS moves and store them in a database. Stay tuned for updates.

 
by Janeth Kent Date: 15-05-2023 javascript hits : 10830  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.

 
 
 

Related Posts

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Clicky