Sort list 1 by sorting 2nd list using Jquery UI sortable

|
| By Webner

How to sort the 1st list of HTML elements by sorting the 2nd list of HTML elements using Jquery UI sortable?

Problem: I am creating two HTML lists using Div elements in my project and I want to change the position of elements in the first list on change of sequence/position of elements in the second list. Problem is that when we use jquery UI, we can make HTML elements sortable individually but not relatively.

Solution:

<body>
 <div id="list1">
    <div class="l1">One</div>
    <div class="l1">Two</div>
    <div class="l1">Three</div>
    <div class="l1">Four</div>
    <div class="l1">Five</div>
    <div class="l1">Six</div>
  </div>
<div id="list2">
    <div class="l2">One</div>
    <div class="l2">Two</div>
    <div class="l2">Three</div>
    <div class="l2">Four</div>
    <div class="l2">Five</div>
    <div class="l2">Six</div>
  </div>
   </body>

Create two lists in HTML file with different ids or class as shown below:

Html page will look like as shown below with some CSS:

When we will reposition element of list 2 then list 1 will automatically be sorted with respect to list1.

To accomplish this following custom code of jquery will be used for the functioning of feature where sortable() method is used to make the div with id “list2” sortable:

 <script type="text/javascript">
  var index_start=0;
     var index_stop=0;
     var swap_element=0;
     var picked_element=0;
     $(document).ready(function(){
          $('#list2').sortable({
           start: function(event, ui){
                   index_start = ui.item.index(); //getting index of picked element
           },
         update: function(event, ui) {
              index_stop = ui.item.index(); //getting index where element is dropped
/*Below steps will fetch the elements from List1 based on original Index ofpicked element in List2
 and its dropped Index position*/
             picked_element = $('.l1:eq('+index_start+')');                   
swap_element = $('.l1:eq('+index_stop+')');  
                   
              swap_element.replaceWith(picked_element); 
          //replaceWith method of javascript removes the picked_element from its original    
          //position & replaces swap_element with picked_element
                   if(index_start > index_stop)
                         picked_element.after(swap_element);
                   else
                         picked_element.before(swap_element);
              },
      });
   });
</script>

When we start sorting of an element the start() method is called in which we are getting an index of position from where we have to start shifting the element. At sorting update() event which gets fired at the drop of the element, we will fetch the index of the element where it is placed and then we will change the position of elements in first list list1.

Leave a Reply

Your email address will not be published. Required fields are marked *