Preventing Redropping: A jQuery Drag and Drop Feature to Ensure Dropped Elements Stay Put

After implementing Drag & Drop functionality using jQuery, I have encountered a specific issue.

The problem: When the dropped element (drag 1) is removed from the droppable container, it reverts back to the draggable container. Subsequently, attempting to drop the same element (drag 1) again into the droppable container fails.

I am seeking assistance in resolving this issue. Any help would be greatly appreciated.

Here is my code:

HTML:

<div class="drag-item">
    <div class="cs-drop">drag 1 <a href="#"> remove</a>

    </div>
    <div class="cs-drop">drag 2 <a href="#"> remove</a></div>
    <div class="cs-drop">drag 3 <a href="#"> remove</a></div>
</div>
<div style="clear: both;"></div>
<div class="drop-container">drop here</div>
<div class="drop-container">drop here</div>
<div class="drop-container">drop here</div>

JS:

<script>
 $('.cs-drop').draggable({
    revert: true
});
drop();

function drop() {
    $('.drop-container').droppable({
        hoverClass: 'active',
        drop: function (e, ui) {
            $(this).append(ui.draggable);
//            $(this).droppable('destroy');
        }


    });
}

$(".drop-container").on("click", ".cs-drop a", function () {
    $(this).closest('.cs-drop').fadeOut(200, function () {
        $('.drag-item').prepend($(this).clone().css('display','block'));
        $(this).remove();
    });
});
</script>

CSS:

<style type ="text/css">
  .cs-drop {
    padding: 40px 25px;
    border: 1px solid red;
    float: left;
}
.drop-container {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    float: left;
}
.drop-container.active {
    background-color: red;
}
</style>

Answer №1

By adding a cloned version of the dropped element back, you encounter issues because the draggable functionality is not initialized on the clone.

$(".drop-container").on("click", ".cs-drop a", function () {
    $(this).closest('.cs-drop').fadeOut(200, function () {
        $('.drag-item').prepend($(this).css('display', 'block'));
    });
});

See it in action: Fiddle


Another approach is to reinitialize the draggable behavior on the cloned element

draggable('.cs-drop');
drop();

function draggable(els) {
    $(els).draggable({
        revert: true
    });
}

function drop() {
    $('.drop-container').droppable({
        hoverClass: 'active',
        drop: function (e, ui) {
            $(this).append(ui.draggable);
            //$(this).droppable('destroy');
        }


    });
}

$(".drop-container").on("click", ".cs-drop a", function () {
    $(this).closest('.cs-drop').fadeOut(200, function () {
        var $el = $(this).clone().show().prependTo('.drag-item');
        draggable($el)
    });
});

Check out this demonstration: Fiddle

Answer №2

Check out this Fiddle Demo Try changing the drop function below:

function drop() {
    $('.drop-container').droppable({
        hoverClass: 'active',
        drop: function (e, ui) {
            $(this).append(ui.draggable);
//            $(this).droppable('destroy');
        }
        $('.cs-drop').draggable({
            revert: true
        });
    });
}

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

Guide to dynamically updating text using Jquery

Is there a way to dynamically change text? I want the ability to double-click on text, have it appear in an input field, then clear and rewrite it. Take a look at my initial code snippet Jsfiddle <div id="main_text"> <h1>Change Text</h ...

Tips for creating a MaterialUI list that wraps to the next line?

import React from 'react'; import { List, ListItem, } from '@material-ui/core'; import { makeStyles, createStyles, } from '@material-ui/core/styles'; import clsx from 'clsx'; import VideoCard from './VideoCa ...

difficulty with parsing JSON in jQuery when referencing an external file containing the same data

Looking for help with parsing a json file using jquery? Check out this working sample: http://jsfiddle.net/bw85zeea/ I'm encountering an issue when trying to load "data2" from an external file. The browser keeps complaining that it's an invalid ...

How can I make an absolutely positioned div slide down from a specific area on the page using jQuery's slideDown() function?

I have a website project in progress where the main image on the homepage is of a house with windows and a door. The idea is that when a user clicks on a window, a <div> should appear with some text. Similarly, clicking on the door should trigger a & ...

Tips for ensuring that Breadcrumbs are displayed properly with the noWrap feature

I am currently working on making the MUI component Breadcrumbs responsive. The issue I am facing is that when the Breadcrumbs component fills up all available space, the items shrink and use ellipsis like a Typography component with the noWrap property se ...

Select the first item that is visible and chosen

Currently, I am working with a select list: <option ng-repeat="hour in Hours" value="{{hour.Value}}" ng-show="filterEvent($index)" ng-selected="hour.Value == EventDate || $first"> {{hour.Text}} </opti ...

Using Ajax to return a Post type in c# mvc 4 instead of a value

Hey there, I seem to be encountering an issue that I could use some help with. $.ajax({ type: "POST", url: "/controller/CreateList", contentType: "application/json; charset=utf-8", traditional: true, ...

Avoiding Duplicate Form Submissions Without JavaScript

Currently, I am working on a project where I am implementing the MVC pattern. Upon successful submission of a form, I redirect the user and display a flash message indicating success using session data. Users face no issues when using the back button or re ...

Instructions for transferring files directly from one website to another

Looking at the PHP code snippet provided: <?php $image_cdn = "http://ddragon.leagueoflegends.com/cdn/4.2.6/img/champion/"; $championsJson = "http://ddragon.leagueoflegends.com/cdn/4.2.6/data/en_GB/champion.json"; $ch = curl_init();` $timeout = 0; cur ...

Could anyone explain to me why the "thumbnails" in my code link are not aligning in a row format as intended?

Why are my "thumbnails" not aligning correctly in the row format I want on this code link? <div class="row"> <div class= "col-md-6"> <div class="thumbnail"> <a target="_blank" href="http://codepen.io/ ...

Rendering of @font-face on Windows 7 was executed flawlessly

I have been utilizing @font-face to implement custom fonts on a website. The custom font displays correctly in Firefox, IE, Safari, and Chrome on Mac. However, when viewed on Chrome in Windows 7, the text appears green at 10px instead of black or grey. ... ...

Unlock the secrets of creating an interactive chat room effortlessly by harnessing the power of J

In search of implementing a unique chat room using PHP and JavaScript (Jquery) offering group chat as well as private chat functionalities. The challenge lies in finding a way to continuously update the interface seamlessly, while also displaying 'X ...

Updating the content of newly added elements using AJAX without refreshing the page

In the process of creating a real-time display of Twitter posts, I have managed to successfully fetch new tweets at regular intervals of 10 seconds. These new tweets instantly appear on the feed. However, I also want to continuously update the displayed t ...

ASP.NET ensures that the entire page is validated by the form

Is it possible to validate only a specific part of the form instead of the entire page? Currently, when I try to validate textboxes on the page, the validation is applied to all textboxes. Here are more details: https://i.stack.imgur.com/eowMh.png The c ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

"SelectChange" event for <drop-down menu>

TL;DR How do I monitor changes in the markup of <select> and <option> tags without relying on the .change() event? I am looking for a way to detect any modifications in attributes (disabled="disabled"), values (value="foo" ...

Leveraging the power of jQuery with AJAX operations

In my collection of PHP files, I have three named: index page books user Index Page <link href="colorbox.css" type="text/css" rel="stylesheet" media="all" /> <script type="text/javascript" src="jquery-1.8.2.min.js"></script> <scrip ...

How can you identify the resume of a web application once you return from opening the camera?

I'm working on a web application that utilizes the camera by following steps from this solution: How to access a mobile phone's camera using a web app? However, I am trying to figure out how to implement a callback function once the user return ...

Flame-inspired CSS editor

My current CSS editing workflow goes something like this: I ask for feedback on a page Suggestions are given to make post titles bigger I use Firebug to inspect the post title element I locate the corresponding CSS statement in Firebug (like h2.post_title ...