JQuery UI - Issue with Draggable functionality immediately after dropping it

HTML:

<div class="character_list">
   <div id="draggable" class="character_list_container">
      <div><img  class="1" src="http://ahna.web44.net//img/charas/13.png" /></div>
      <div><img class="2" src="http://ahna.web44.net//img/charas/13.png" /></div>
      <div><img class="3" src="http://ahna.web44.net//img/charas/13.png" /></div>
      <div><img  class="4" src="http://ahna.web44.net//img/charas/13.png" /></div>
      <div><img class="5" src="http://ahna.web44.net//img/charas/13.png" /></div>
      <div><img class="6" src="http://ahna.web44.net//img/charas/13.png" /></div>
   </div>
   <div id="droppable_slots" class="current_team">
      <div id="slot" class="1">1</div>
      <div id="slot" class="2">2</div>
      <div id="slot" class="3">3</div>
   </div>
</div>​

jQuery:

$(function() {
    $("#draggable>div>img").draggable({
        start: function(){
           $(this).css({display: 'none'});
        },
        stop: function(){
           $(this).css({display: 'block'});
        },
        revert: function(dropped) {
           var dropped = dropped && dropped[0].id== "slot";
           if(!dropped) {
              $(this).appendTo($(this).data('originalParent'))
            }
            return !dropped;
        },
        helper: function() { return $(this).clone().appendTo('body').show(); },
        containment: '.sel_screen_left'
}).each(function() {
    $(this).data('originalParent', $(this).parent())
});

$("#droppable_slots>div").droppable({
    drop: function(event, ui) {

        var $this = $(this);
    var content = $.trim($this.html()).length;
    if(content > 0) {
    $this.html("");
    }
        $this.append(ui.draggable);    

        var width = $this.width();
        var height = $this.height();
        var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
        var cntrTop = (height / 2) - (ui.draggable.height() / 2);

        ui.draggable.css({
            left: cntrLeft + "px",
            top: cntrTop + "px"
        });

}
});
});​

Live example: http://jsfiddle.net/CVbzg/3/

In the provided jsfiddle demonstration, there is an issue where once an image is dropped and moved out of the drop zone, it loses its draggable feature instead of reverting back to its original position. Can anyone offer a solution to this problem?

Answer №1

If the droppable loses its draggability after being moved slightly within the drop target, it is due to this specific scenario:

$this.html("");

Basically, when you remove the HTML content of the drop target in the drop handler, it also removes the element that should be re-appended. This results in a syntax error because the element no longer exists, causing the operation to fail and leaving the clone behind while erasing the draggable.

To resolve this issue, consider implementing the following quick fix:

drop: function(event, ui) {

    var $this = $(this);
    if ($this.find('.ui-draggable').length) return; // Prevent overwriting an occupied spot
    $this.empty(); // Using empty() instead of html('') for semantic clarity
    $this.append(ui.draggable);
    // Additional code here...
}

Check out this Fiddle for reference.

This solution ensures that elements cannot overwrite each other within a drop target and avoids issues with re-dropping elements on their own targets.


Alternatively, you can move the previously dropped draggable back to its original position before appending the new one:

drop: function(event, ui) {
    var $this = $(this),
        containsDropped = $this.find('.ui-draggable');
    if (containsDropped.length) containsDropped.appendTo(containsDropped.data('originalParent'));
    $this.empty();

Here's another Fiddle demonstrating this approach.

Just be cautious not to accidentally erase a draggable element in the process. =]

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

Navigate to the initial visible element on the specified webpage via the page hash link

In my handlebars HTML template, I have a partial view that includes different pieces of content for desktop and mobile. I use different CSS classes to hide and show these elements accordingly. <div class='hideOnMobile showOnDesktop'> < ...

What's the best way to merge data from two separate PHP class files into a single file?

As I develop a registration form, I have created three distinct classes: the database file for fetching data from the database, the display file for the HTML templates, and the controller file for getting data from both of these files. My current challen ...

Looking to extract and upload a thumbnail image from an HTML5 video element

I am trying to extract and upload a thumbnail from an HTML5 video tag, Below is my code snippet: var w = 135;//video.videoWidth * scaleFactor; var h = 101;//video.videoHeight * scaleFactor; var canvas = document.createElement('canvas&apo ...

Highlighting menu elements when landing on a page and making another menu element bold upon clicking in WordPress

I've been searching extensively for a solution to this issue. I'm trying to make the menu item DE appear bold when entering the site, and if I click on EN, I want DE to return to normal (thin) font while EN becomes bold. You can find the site he ...

What is the best method for preventing a form's ajax events from triggering when a link inside the form is clicked?

I am working with an ajax form that looks like this... <form action="/whatever" method="POST" id="blerg"> </form> There is an ajax event attached to it for when the form is submitted: $("#blerg").bind(&a ...

Could a jquery slick carousel be used to modify the body background of a webpage?

Is it possible to have one of the divs in a carousel change the background of the page, while the carousel is active on that specific div? if ($('.carousel').slick('slickGoTo', 1)){ //if slick is on slide index 1 //change to another pag ...

I successfully managed to ensure that the splash screen is only displayed upon the initial page load. However, I am now encountering an issue where it fails to load again after I close the page. Is there any possible solution

After successfully implementing a splash screen that only plays once on page load, I encountered an issue. When I close the tab and revisit the page, the splash screen no longer plays. Is there a way to fix this problem? Perhaps by setting a time limit for ...

The POST request results in a JSON response containing a null value

Question A: How to fix issues with JSON content type in PHP scripts? $(document).ready(function() { $("#submit_form").on("click",function(){ var json_hist = <?php echo $json_history; ?>; $.ajax({ type: "POST", ...

Customize your radio buttons to display as stylish boxes with Bootstrap

Check out my Fiddle here... The radio buttons are displaying correctly in the fiddle. <div class="element-radio" title="Do you want to float the text to the left, right, or not at all?"><h4 class="title" style="font-weight: bold;">Float (left ...

sending form data using JQuery Ajax

Trying to pass two values to a PHP file through AJAX Here is my current code: PHP : <?php $name="Name with spaces"; ?> JS : var yourMessage = $("input#message").val(); $.ajax({ type: "POST", url: "send_message.php", data: "yourNa ...

Retrieve Browser Screen Width and Height using MVC3 Razor in the View

I am facing a challenge on my website where I need to generate a Bitmap dynamically and ensure it is rendered according to the width and height of the browser so that there are no overflow issues on the page. Although I have successfully created an image ...

Tips for creating a textfield with height that responds dynamically in Material UI

I am trying to create a textfield with a responsive height that adjusts itself based on the size of its parent grid when the browser window is resized. I have been searching for a solution and came across this helpful post on Stack Overflow about creating ...

Enhance autocomplete suggestions by including supplementary information

A unique feature on my website is a field that provides autocomplete options for person names, such as "Obama, Barack" or "Lincoln, Abe." These individuals also come with additional attributes, like "Birthplace" and "Phone number." I want the selected opt ...

What is the correct method for notifying the progress of time using jQuery?

I'm looking for a way to display the processing time of my PHP code using jQuery Here's an example of my PHP code : <?php //some queries to database ?> Below is my jQuery code: $.ajax({ type: "POST", url: "action. ...

Organizing list items into vertical columns

Could you help me with UL/LI syntax and how to create a wrapping list? For example, I would like to display: 1 2 3 4 5 6 As: 1 4 2 5 3 6 Currently, I have a header, content, and footer all set with specified heights. I want the list to wrap when ...

Parsing a text file containing various data entries, converting them into objects, and then storing them in an array

I need assistance with parsing and storing information from a file containing multiple DNA sequence ID's and their sequences. My goal is to create an object for each entry: function processSequences(event) { //Retrieve the file from the HTML inpu ...

Enhance your website with a customizable language selection feature using HTML and CSS

Currently, I am in the process of creating a dynamic language selection feature using HTML and CSS. Initially, this is what it looks like: https://i.stack.imgur.com/bhnaA.png Upon hovering over it, this is the effect I want to achieve: https://i.stack.i ...

What is the reason behind PHP files not being able to utilize gzip compression?

I have a pair of files on my server, both named test.html and test.php, containing identical content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>TEMPLATE</title> </head> <body> ...

What is the best way to adjust the content of a Bootstrap Column to be at the bottom of the column

Currently diving into the world of Bootstrap for my personal website, I'm encountering a challenge in aligning the content of my sidebar to the bottom. My quest for a solution led me through numerous threads without success. <!-- wordsmith: < ...

Cause an element to extend beyond others when the viewport reaches its limit

My design dilemma involves two squares: a blue one that will expand to contain things totaling 800px, and a red one that must always remain fully visible. When narrowing the viewport, the red square should overlap the blue square, rather than disappearing ...