4

Sorting elements with SortableJS and storing them in localStorage

 2 years ago
source link: https://www.ma-no.org/en/programming/javascript/sorting-elements-with-sortablejs-and-storing-them-in-localstorage
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sorting elements with SortableJS and storing them in localStorage

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 : 0  

</article


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK