When no items are available, the drag and drop functionality does not function

When I am performing drag and drop between two containers, everything functions correctly when there is at least one element present in the container. However, if I remove all elements from either container and try to drag them back, the operation fails.

HTML:-

<div class="portlet-body ui-sortable" id="sortable_portlets">
   <div class="sortable row-fluid pull-left packlistWrap excersissestoaddtopac">First DIV
      <div class="portlet portlet-sortable light bordered packlistupdate packlist" tag-id="2" video-id="4">
         <div class="portlet-title">
            <div class="row">
               <div class="col-md-6"><span>TAG A</span></div>
               <div class="col-md-6"><span></span></div>
            </div>
         </div>
      </div>
   </div>


<hr>
<hr>
<hr>
<hr>

   <div class="mid-title"><span class="caption-subject font-green sbold uppercase ">SECOND DIV</span></div>
   <div id="excersisesinpac">
      <div class="portlet portlet-sortable light bordered packlist" video-id="2">
         <div class="portlet-title">
            <div class="row">
               <div class="col-md-6"><span>TAG B</span></div>
               <div class="col-md-6"><span></span></div>
            </div>
         </div>
      </div>


        <div class="portlet portlet-sortable light bordered packlistupdate packlist" tag-id="2" video-id="4">
         <div class="portlet-title">
            <div class="row">
               <div class="col-md-6"><span>TAG A</span></div>
               <div class="col-md-6"><span></span></div>
            </div>
         </div>
      </div>

   </div>
</div>

javaScript:-

var PortletDraggable = function () {

    return {
        //main function to initiate the module
        init: function () {

            if (!jQuery().sortable) {
                return;
            }

            $("#sortable_portlets").sortable({
                connectWith: ".portlet",
                items: ".portlet", 
                opacity: 0.8,
                handle: '.portlet-title',
                coneHelperSize: true,
                placeholder: 'portlet-sortable-placeholder',
                forcePlaceholderSize: true,
                tolerance: "pointer",
                helper: "clone",
                tolerance: "pointer",
                forcePlaceholderSize: !0,
                helper: "clone",
                cancel: ".portlet-sortable-empty, .portlet-fullscreen", // cancel dragging if portlet is in fullscreen mode
                revert: 250, // animation in milliseconds
                update: function(b, c) {
                    if (c.item.prev().hasClass("portlet-sortable-empty")) {
                        c.item.prev().before(c.item);
                    }   
                },


                stop: function(event, ui) {
                                }
            });
        }
    };
}();

jQuery(document).ready(function() {
    PortletDraggable.init();
});

https://jsfiddle.net/33keyjxx/26/

Answer №1

When using the sortable() method, ensure to include the following:

dropOnEmpty: true,

$(".draggable").draggable({
            revert: "invalid",
            zIndex: 100,
            opacity: 0.35,
            containment: "window",
            scroll: false,
            dropOnEmpty: true,
            stop: function (event, ui) {
                // cancelFollow = true;
                $(event.toElement).one('click', function (e) {
                    e.stopImmediatePropagation();
                });
            }
        });

Answer №2

To achieve the desired result, you can modify the code in the following way. I introduced two new class type selectors .packlistWrap and .mid-title, and also made a change to connectWith.

$("#sortable_portlets") =>

$(".packlistWrap, .mid-title, #sortable_portlets")

connectWith: ".packlistWrap, .mid-title",

The rest of the code remains unchanged.

$(".packlistWrap, .mid-title, #sortable_portlets").sortable({
  connectWith: ".packlistWrap, .mid-title, .portlet",
  dropOnEmpty: true,
  items: ".portlet",
  opacity: 0.8,
  handle: '.portlet-title',
  coneHelperSize: true,
  placeholder: 'portlet-sortable-placeholder',
  forcePlaceholderSize: true,
  tolerance: "pointer",
  helper: "clone",
  tolerance: "pointer",
  forcePlaceholderSize: !0,
  helper: "clone",
  cancel: ".portlet-sortable-empty, .portlet-fullscreen", // cancel dragging if portlet is in fullscreen mode
  revert: 250, // animation in milliseconds
  update: function(b, c) {
    if (c.item.prev().hasClass("portlet-sortable-empty")) {
      c.item.prev().before(c.item);
    }
  },
  stop: function(event, ui) {}
});

Answer №3

Within your code snippet, the line

$("#sortable_portlets").sortable(...)
is currently targeting a single element. To achieve the desired functionality, you should be targeting the two separate sortable containers specified as #excersisesinpac and .excersissestoaddtopac in your case. In the example provided below, I have introduced the class sortable to the #exercisesinpac element (as the .excersissestoaddtopac already has this class). Consequently, I have adapted the invocation of $.sortable to target both elements with the .sortable class by using
$("#sortable_portlets .sortable").sortable(...)
.

var PortletDraggable = function() {

  return {
    //main function to initiate the module
    init: function() {

      if (!jQuery().sortable) {
        return;
      }

      $("#sortable_portlets .sortable").sortable({
        connectWith: ".sortable",
        items: ".portlet",
        opacity: 0.8,
        handle: '.portlet-title',
        coneHelperSize: true,
        placeholder: 'portlet-sortable-placeholder',
        forcePlaceholderSize: true,
        tolerance: "pointer",
        helper: "clone",
        tolerance: "pointer",
        forcePlaceholderSize: !0,
        helper: "clone",
        cancel: ".portlet-sortable-empty, .portlet-fullscreen", // cancel dragging if portlet is in fullscreen mode
        revert: 250, // animation in milliseconds
        update: function(b, c) {
          if (c.item.prev().hasClass("portlet-sortable-empty")) {
            c.item.prev().before(c.item);
          }
        },


        stop: function(event, ui) {



        }


      });
    }
  };
}();

jQuery(document).ready(function() {
  PortletDraggable.init();
});
body {
  padding: 1.25em;
}

div {
  position: relative;
}

.wire {
  position: relative;
  margin: 1.25em;
  padding: 1.25em;
  border: 1px solid;
}

.wire::before {
  padding: 0 1em;
}

.wire::before {
  position: absolute;
  top: -1.25em;
  left: 0;
  padding: 0 1em;
  color: white;
}

#sortable_portlets::before {
  content: "#sortable_portlets";
  background-color: #B683C3;
}

.sortable::before {
  content: ".sortable";
  background-color: #6373B6;
}

.portlet {
  min-width: 100px;
}

.portlet::before {
  content: ".portlet";
  background-color: #E06D10;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<div class="portlet-body ui-sortable wire" id="sortable_portlets">
  <div class="sortable row-fluid packlistWrap excersissestoaddtopac wire">
    <div class="portlet portlet-sortable light bordered packlistupdate packlist wire" tag-id="2" video-id="4">
      <div class="portlet-title">
        <div class="row">
          <div class="col-md-6"><span>TAG A</span></div>
          <div class="col-md-6"><span></span></div>
        </div>
      </div>
    </div>
  </div>

  <div id="excersisesinpac" class="sortable wire">
    <div class="portlet portlet-sortable light bordered packlist wire" video-id="2">
      <div class="portlet-title">
        <div class="row">
          <div class="col-md-6"><span>TAG B</span></div>
          <div class="col-md-6"><span></span></div>
        </div>
      </div>
    </div>


    <div class="portlet portlet-sortable light bordered packlistupdate packlist wire" tag-id="2" video-id="4">
      <div class="portlet-title">
        <div class="row">
          <div class="col-md-6"><span>TAG A</span></div>
          <div class="col-md-6"><span></span></div>
        </div>
      </div>
    </div>

  </div>
</div>

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

In the realm of JavaScript, consider logging a message to the console if the array value happens to be

I'm facing an issue with the code below. My goal is to log 'empty array value' whenever there is an empty value, but it's not functioning as expected. Can anyone advise me on what the value of an empty array item is and how I can modify ...

Trying to conceal the scrollbar on MS Edge and Firefox?

Currently, I am working on a scrollable menu that requires the scrollbar to be hidden. In Chrome, I have achieved this by using the following code: .menu::-webkit-scrollbar { display: none; } I would like to know if there is an equivalent solution ...

When the 'object' value is 0, the 'level' input will not appear on the screen

Task at hand: Hide the 'level' input when the 'object' value is 0. Current situation: input type="text" id="level" input type="text" id="object" My attempt: var lvl = do ...

What could be the reason for the lack of definition of the `pieceOfText

My latest project involves a fun guessing game centered around decrypting text, but I've hit a snag with a variable in my JavaScript code. This variable, known as pieceOfText, should be assigned a random piece of text from an array containing 3 encode ...

Ways to reset input fields following form submission

I've been trying to figure out how to clear the input fields once the form is submitted, but for some reason, the input data remains there even after each submission. I'm using ajax jquery form. Any ideas on how to resolve this issue? Thank you ...

What is the method for retrieving a class's property without creating an object instance?

Currently, I am working with a class setup like this: class MyClass { constructor(privateInfo) { this.a = "a"; this.b = "b"; } myMethod() { return privateInfo; } } It seems that the privateInfo variable needs to be ...

Personalized Bootstrap grid rows and columns

https://i.sstatic.net/R0yFY.png As a beginner in Bootstrap, I am having trouble achieving this specific layout in Bootstrap 4 grid. The areas marked in red are not appearing as expected. Here is what I have attempted so far: <div class="row"> ...

Encountered an error while attempting to convert react-native-reanimated-65-jsc.aar

ERROR: App installation failed after 19 seconds Failed to install the app. Ensure your Android development environment is properly set up. Follow this link for setup instructions: https://reactnative.dev/docs/environment-setup. Erro ...

Unusual gaps of white space appearing between React components

Currently developing a small web application with multiple components. The backend functionality is all set, but encountering an unusual styling issue. Specifically, noticing a white space appearing between each component without any clear reason. This ga ...

Display the names of the files and give the user the option to delete them prior to finalizing the form submission

I'm currently developing a webpage where users can upload files and send them along with a message. One issue I've come across is that when attempting to upload a file or send an attachment (single or multiple), the code snippet below is required ...

Having trouble with jquery AJAX get function experiencing undefined error when processing a valid JSON response

Hey team, I am relatively new to working with jQuery and I've run into a problem with a valid JSON response that's causing an unknown error. My project is a web-based C# MVC with a SQL Server backend database, using EF. Here is the code snippet ...

Styling Overflow in Coda Slider using CSS

Currently utilizing the Coda Slider for my project. For those unfamiliar with the Coda Slider, it initially hides the overflow-x position until a tab is clicked. This triggers an animation that slides the hidden DIV in either from the right or left side. ...

When setting up a new nodejs/express project, I encountered an issue where the fresh installation would fail

After setting up node and express on my new development server, I created a test application by running the command below: dev-server15:/var/www# express mytest create : mytest create : mytest/package.json create : mytest/app.js ... The npm ...

What steps do I need to take to integrate an Instagram Reel onto my website using the embed code?

I am currently facing an issue with embedding reels on my website. Even though I can view the reel, I am unable to playback the video. When embedding a video or carousel on my website, I have no trouble viewing it. However, when it comes to reels, all I se ...

Avoid using the jQuery.get() function

$.get('./mods/webim_offline_email.php', {name: $('#webim_name').val(), email_address: $('#webim_email_address').val(), msg: $('#webim_msg').val()}, function (data){ alert(1); $('#webim_offline_form' ...

Creating a dropdown menu using jQuery

I have a situation where I am linking a dropdown menu to the "onChange" event of a textbox. The functionality works as expected, however, when I click the button associated with it, the click event is not triggered. Below is the script being used: <sc ...

Why does the Node.js REST API keep throwing errors after I try to create just one record?

I encountered a back end issue recently. I have developed a simple API with just a post endpoint. The intention is to post data using the req.body. Oddly enough, it works perfectly fine the first time but when I attempt it again, I receive an error message ...

"Unraveling the Mysteries of the Basic JavaScript

This scenario involves the task of eliminating all paragraphs. Despite using a for-loop, not all paragraphs were successfully removed. The initial paragraph remained unaltered. http://codepen.io/vinhnghi223/pen/jnkzh article=document.getElementsByTagName( ...

Enhancing user experience with scroll snapping within nested components/elements

https://i.sstatic.net/PzNmP.gif Looking at the gif, you can see a large scrollable container with various main blocks ('Attack', 'Release', etc.) housed within it. Each main block contains one or multiple columns (such as 'Attack ...

What is the method for setting a fixed size for a Bootstrap container?

Bootstrap 4 is the framework I am currently using. Below is the HTML code I have written: <div class="sprite container d-inline-block bg-info rounded p-1"> <span class="sprite-span-level">Top-right text over image</span> <img cl ...