Top method for setting up two drag-and-drop lists with one being sortable and the other automatically resorting upon dropping items?

In a given situation I am facing, there is a long list of columns represented by <li> elements in two <ul> lists. On the left side are all available fields that can be selected by users, while on the right side users drag and drop desired fields from the left list to build an ordered list of columns for a dynamic report.

By using the JQueryUI Sortable() method, I have successfully created lists for dragging and dropping these column elements as needed. The functionality works flawlessly when moving content from the left list to the right, allowing users to order the columns themselves.

However, if a user decides not to include a previously added column and drags it back from the right list to the left, I would like the item to return to a specific pre-determined position within the left-side Sortable() list, rather than being placed below where it was dropped.

What is the best way to address this requirement? Should I utilize a JQueryUI Sortable() object for the container of columns on the left side and reorganize the data upon dropping, or is there a more suitable JQuery tool for this task? If opting for defining the left-side list as a Sortable() object, how should I adjust it to ensure proper reordering post-drop operation?

I have used this JSFiddle to set up the basic mechanics of the lists. While the right-side list functions as intended, I aim for the left side to maintain a sorted order based on a specified value for forced sorting. For instance, in this example, the left side should consistently sort based on the data-sort attribute defined in each <li>.

Answer №1

Arrange all the dropped items in #left-list based on the specific data-sort attribute. Use the update callback function, which triggers with each update instead of using the stop function.

$("#left-side").sortable({
  connectWith: "#right-side",
  update: function(e, info) {
    $(this).children('li').sort(function(a, b) {
        return +a.dataset.sort - +b.dataset.sort;
    }).appendTo(this);
  }
});
$("#right-side").sortable({
  connectWith: "#left-side"
});
// code to assign appropriate data-sort attribute to each LI
$("#left-side, #right-side").find('li').attr('data-sort', function() {
  return $(this).index('body ul.ui-sortable li');
});
ul {
  border: 1px solid Black;
  width: 200px;
  height: 200px;
  display: inline-block;
  vertical-align: top;
}
li {
  background-color: Azure;
  border-bottom: 1px dotted Gray
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<h1>Click items to select them</h1>
<ul id="left-side">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>
<ul id="right-side">
  <li>Four</li>
  <li>Five
  </li>
  <li>Six</li>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

The smoothness of jQuery animations is not consistent

I've been working on mastering the art of scheduling animations using JavaScript, in particular with the assistance of jQuery. In an attempt to create a blinking effect for some h1 tags, I noticed that the animation was not running smoothly. It would ...

Spring load without CSS

Upon successful login, I am redirected to my main site using the following controller: //Login Success @GetMapping("/login-success") public ModelAndView loginSuccess() { return new ModelAndView("/cont/home.html"); } The URL for this redirection i ...

What is the best way to dynamically pass props to the styles hook in Material UI?

Looking for a way to dynamically add background images to div elements? I'm currently iterating over an array of objects and returning divs, but I'm not sure how to set the background image based on the image URL in each object. Can anyone help m ...

Is there a way to use jQuery to animate scrolling on a mobile web browser?

I'm trying to make the page scroll to a specific position when a button is clicked. The code I currently have works fine on browsers like Chrome and IE, but doesn't seem to work on any mobile browser. Below is the code snippet I am using: $("#p ...

Unable to update meta tags in index.html on GitHub Pages using create-react-app (CRA)

When using GitHub Pages, it overrides my create-react-app's index.html with its own file. The original index.html includes important meta tags, but GitHub's version does not. Unfortunately, I am unable to modify the metadata of GitHub's in ...

Nested ng-repeat for dynamic variable rendering

I am facing an issue where I have a nested ng-repeat directive. I am attempting to create a dynamic second ng-repeat, using a key from the first one, but the current syntax is not working. Is there a different way to achieve this? Perhaps a different nota ...

What could be causing the Ajax code to not activate when clicking or loading?

Appreciate your support. I am venturing into the world of coding MVC and attempting to create a page that will generate a parent-child loop with data sourced from JSON (MenuHandler.ashx). The JSON data has been tested successfully, but there seems to be a ...

Utilizing Firebase Cloud Firestore: A guide to programmatically handling indexes

Transitioning from Firebase Realtime Database to Cloud Firestore has presented some challenges in implementing "complex" queries across collections. Despite this, I am determined to make it work. My current setup involves using Express JS and Firebase Adm ...

Running a Node.js server on a public IP address while utilizing socket.io

Take a look at the server code snippet below: express = require('express'); app = express(); app.use('/', express.static(__dirname + '/')); http = require('http').Server(app); io = require('socket.io')(htt ...

Getting the most out of the fastest-validator package: Implementing multiple patterns and custom messages

Utilizing the powerful fastest-validator library for validation purposes. I have a requirement where the password field must contain at least one character and one number. Along with this, I am in need of specific messages for validating these conditions ...

What could be causing the PAGE CSS to malfunction?

I am looking to export HTML text as a word document with A4 size and portrait orientation. My JavaScript currently allows me to export the text, but it appears like a webpage format rather than in A4 or portrait mode. I have tried adding @page CSS styling ...

In Firefox, resizable child elements in a flex container cannot be resized

Exploring the realm of flexbox has brought me to a bit of a roadblock with a layout like this one: https://jsfiddle.net/5b0pLgkj/ Everything seems to be running smoothly in Chrome and Safari, where children elements can be resized and fill up the availabl ...

Using PHP code to pass a value to JavaScript

I have both PHP and JavaScript code on my page, and I need to retrieve a value from PHP into my JavaScript code. Below is my JavaScript code: <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "Bread ...

Identify and emphasize fields that contain identical, non-empty values

I am attempting to compare the values of textboxes and highlight them if they are the same, excluding any textboxes that are empty. Feel free to view an example on this JSFiddle link: http://jsfiddle.net/qjqa1et2/61/ Below is the jQuery code I am current ...

The HTML form label offers a choice between two alternatives

My usual method of styling forms involves organizing elements like this: <label for="CompanyNameTextBox"> <span>Company</span> <input name="CompanyNameTextBox" type="text" id="CompanyNameTextBox" /> </label> This set ...

Strategies for managing unpredictable time series data visualization

I am currently working on graphing data retrieved from an API. You can find a sample of the data here. [ { "id": 10516560, "username": "acrawford69", "avatar_url": "https://a.ppy.sh/1 ...

Creating dynamic rows for Firebase data in React BootstrapTable can be accomplished by dynamically rendering each row

Hey everyone, I'm currently working on a web app project where I am creating a table. Below is the code snippet for it: class Table1 extends Component { render() { return ( <div> <BootstrapTable data={this.props.data}> ...

Finding a solution to this issue in Angular will consistently result in a false outcome

Can anyone explain why I keep getting the error message "This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap" whenever I try to compare charTypeEnum with ChartType.text? ...

Calculate the duration in seconds using the console

Is it possible to display the time of an action in seconds instead of milliseconds using console.time? Below is my code: console.log('start load cache'); console.time('cache load ok executed in') // loading from mongo console.timeEnd( ...