Creating a draggable element that can be reverted once it is added to a list and has a dynamically generated inline style tag

There are numerous questions related to this topic on stackoverflow, such as How to make dynamically added list elements draggable in jQuery?

However, I am attempting something unique. I am adding my list elements during the page load as shown below:

<ul id="CreateCustomerListUL">
              <li class="custList" draggable="true" data-id="200001" data-pnumber="1234567890" data-accountname="Nidhi Sales"><strong>Nidhi Sales</strong> <p>1234567890</p></li>                 
              <li class="custList" draggable="true" data-id="200002"  data-pnumber="1234567890" data-accountname="Dhanashree Traders"><strong>Dhanashree Traders</strong> <p>1234567890</p></li>                  
              <li class="custList" draggable="true" data-id="200003"  data-pnumber="1234567890" data-accountname="Amrut Traders" style="display: list-item;"><strong>Amrut Traders</strong> <p>1234567890</p></li> 
</ul>

Once the list page has loaded, each item is dragged and dropped into a dataTable. The following code is automatically generated after drag and drop:

<tbody id="CustListTableBody">
<tr role="row" class="odd"><td class="sorting_1">1</td><td class="">Dhanashree Traders</td><td>1234567890</td><td><span class="glyphicon glyphicon-remove deleteRow" data-name="Dhanashree Traders" data-number="1234567890" data-id="200002"></span></td></tr>
<tr role="row" class="even"><td class="sorting_1">2</td><td class="">Nidhi Sales</td><td>1234567890</td><td><span class="glyphicon glyphicon-remove deleteRow" data-name="Nidhi Sales" data-number="1234567890" data-id="200001" ></span></td></tr>
<tr role="row" class="odd"><td class="sorting_1">3</td><td class="">Amrut Traders</td><td>1234567890</td><td><span class="glyphicon glyphicon-remove deleteRow" data-name="Amrut Traders" data-number="1234567890" data-id="200003" ></span></td></tr>
</tbody>

The datatable will look like this: The droppable code is as follows:

$('#CustListTable').droppable({             
            onDrop:function(e,source){
            var t = $('#CustListTable').DataTable();
             var rowCount = t.rows().data().length +1;              
                var custName = $(source).attr('data-accountname');
                var custNumber = $(source).attr('data-pnumber');
                var custId = $(source).attr('data-id');             
                var deleteRow = '<span class="glyphicon glyphicon-remove deleteRow" data-name="'+custName+'" data-number="'+custNumber+'" data-id="'+custId+'"></span>';                                                    

               t.row.add( [ rowCount, custName, custNumber, deleteRow]).draw();   

                $(source).remove();                     
            }               
        });

I am deleting the row after clicking on the cross symbol in the third column. The code for deleting the row from the datatable is:

$('#CustListTable').on('click','.deleteRow',function() {                  
        var t = $('#CustListTable').dataTable();
             var name=$(this).attr('data-name');
            var pNumber = $(this).attr('data-number');
            var id = $(this).attr('data-id');
            var item = '<li class="custList" draggable="true" data-id="'+id+'"data-pnumber="'+pNumber+'" data-accountname="'+name+'"><strong>'+name+'</strong> <p>'+pNumber+'</p></li>';

            var $element = $('<li class="customerList" draggable="true" data-id="'+id+'"data-pnumber="+pNumber+" data-accountname="'+name+'"><strong>'+name+'</strong> <p>'+pNumber+'</p></li>');
    $element.draggable().resizable();
    $('#CreateCustomerListUL').append($element);
          var row = $(this).closest("tr").get(0);
         t.fnDeleteRow(t.fnGetPosition(row));                 
    });

Everything is functioning correctly up to this point. However, if I try to drag the same element and the drop fails, it does not revert back to its original position. The issue seems to be caused by inline styling generated when dragging starts, particularly the style="position:absolute;" attribute. I have attempted various solutions from stackoverflow but haven't been successful in resolving this reverting problem.

I have tried the following code snippet for reverting the drag:

$('#CreateCustomerListUL li').draggable(
  {revert : function(event, ui) { 
    alert('Hello'); 
    $(this).data("uiDraggable").originalPosition = { top : 0, left : 0 }; 
}});

Answer №1

The documentation suggests using the following option when working with draggable elements:

.draggable({
  revert: "invalid"
});

When set to "invalid", the element will only revert if it has not been dropped on a droppable target. Conversely, setting it to "valid" will result in reverting only if it has been dropped on a valid target.

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

Buefy: Secure the header of the table in place while allowing the rows to scroll freely

How can I make the header of the table component stay fixed while allowing only the rows to scroll? ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

Experimenting with animating an element through onClick event using JavaScript

I would like to create an animated div using JavaScript that activates on click. <div class="Designs"> <p>Designs</p> <div class="Thumbnails" data-animation="animated pulse"> <a href=" ...

Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000? HTML: <!DOCTYPE html> <html> <meta name="viewport" content="width=dev ...

Dealing with multipart/form-data in Express using cloud functions in the upcoming year of 2022

Seeking advice on handling multipart/form-data requests in an Express backend with Google Cloud Functions in 2022. Despite numerous attempts, the issue remains unresolved after extensive research and testing various methods that work locally but fail when ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

When a child is added to a parent in Angular UI Tree, it automatically appears in all parent nodes as well

I've been experimenting with the drag and drop feature of Angular UI Tree, and I've encountered a puzzling issue. The JSON data is fetched from my services. Upon receiving it in my controller, I need to format it correctly by adding an empty arra ...

Automatically update Dropdown options with value and text through an ajax json request

I am working on dynamically populating a dropdown list with text and values fetched using an ajax call to retrieve a JSONObject. While my current code successfully populates the dropdown, I need the value to be different from the text as I intend to store ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

Preventing reference problems with AngularJS by employing the "copy()" method

I have a situation where I need to display a list of items with an "edit" button next to each one. When the user clicks on the edit button, an Angular UI modal window opens allowing them to make changes to the item. The problem I encountered was that any c ...

Pass the name and value of the selected option to AJAX

My goal is to use AJAX to send both the name and value of a selected option from a dropdown menu. This will allow me to launch a SQL request including the selected option. This is what I have so far: jQuery: $('#form_stadt_kanton').select(func ...

Exploring the hover functionality in GetOrgChart

Exploring mouse hover functionality in Getorgchart view. Looking to implement the mouse hover and mouse out events in Getorgchart view. Can I access the org chart element details during mouse hover/leave actions? ...

Disable, Hide, or Remove Specific Options in a Single Dropdown Selection

A challenge I am facing involves creating a form with multiple select options that need to be ranked by the user from 1-8. However, I am encountering some difficulties in hiding, removing, or disabling certain select options. Below is an excerpt from my f ...

Steps for repairing a button positioned at the top of a nested container within a form

My search form includes side filters to help users narrow down their search, with the results appearing on the right. This is just a basic example, as my actual setup involves more filters. However, there is one issue – users have to scroll down the pag ...

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

The JSON reviver function is still not returning anything even when explicitly using the return

function _quotedText(data, config) { var pathKeys=config.customKey; console.log(pathKeys); //prints os_platform var inAuth_data=(JSON.parse(JSON.parse(JSON.parse(data["event.fields.custom_fields.inauth_device_data"])), (key, value) =& ...

Components for designs using Meteor and Blaze

Hello, currently I am working with Meteor and Blaze. Here is how my routes are set up: FlowRouter.route('/software', { name: 'software', action(params, queryParams) { BlazeLayout.render('App_body', {main_ ...

It is not permitted to incorporate the navbar.html file into any other modules

As someone new to web development, I have been facing challenges while working with Django This is the code for my project's modules. {% include 'navbar.html' %} <h1>projects template</h1> <p>Lorem Ipsum is simply dummy ...

Disappearance of the second level in a CSS dropdown menu

I am currently working on creating a dropdown menu using only CSS. Check out this example I'm using: http://jsfiddle.net/DEK8q/8/ My next step is to center the menu, so I added position-relative like this: #nav-container { position: rela ...

How can I completely alter the content of aaData in jquery.dataTables?

Looking to completely change the content of a datatable purely from a javascript perspective, without relying on Ajax calls. I've attempted using the following script: oTable.fnClearTable(); oTable.fnAddData(R); oTable.fnAdjustColumnSizin ...