Detach a JQuery drag and drop element from a location without removing or concealing it

Currently working on a project that involves moving divs into a designated area, resizing them to fit the area, and then snapping them into place.

Encountering an issue where when bottom items are removed from the area, they seem to "jump" up on the screen as if compensating for the space occupied by other items. For a better understanding, a JSfiddle example is included below.

To replicate the issue, try placing two items in the right area and then removing the bottom one - you'll notice the item you're holding moves upward on the screen once taken out of the area.

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Creator</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/styles.css">
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
    </head>

    <body>
        <div class="drag-area">
            <div id="snaptarget" class="ui-widget-header">
            </div>

            <br style="clear:both">

            <div id="draggable" class="draggable ui-widget-content">
                <p>A</p>
            </div>

            <div id="draggable2" class="draggable ui-widget-content">
                <p>B</p>
            </div>

            <div id="draggable3" class="draggable ui-widget-content">
                <p>C</p>
            </div>

            <div id="draggable4" class="draggable ui-widget-content">
                <p>D</p>
            </div>

            <div id="draggable5" class="draggable ui-widget-content">
                <p>E</p>
            </div>
        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

CSS:

.drag-area {
  min-height: 100vh;
    display: grid;
    grid-template-columns: 300px auto 300px;
    grid-template-rows: 150px auto;
}

.draggable {
    grid-column: 1;
    grid-row: 1;
  width: 80px;
  height: 80px;
  display: inline-block;
  margin: 0 10px 10px 0;
  font-size: .9em;
}

.ui-widget-header p,
.ui-widget-content p {
  margin: 0;
}

#snaptarget {
  width: 173px;
    height: 100vh;
    grid-column: 3;
  position: relative;
}

jQuery/JS:

$(function() {
  $(".draggable").draggable();
    $(".draggable").resizable();
  $("#snaptarget").droppable({
    accept: ".draggable",
    drop: function(e, ui) { 
        var $item = ui.draggable;
        $item.appendTo($(this)).css({
            margin: 0,
            position: "relative",
            top: 0 + "px",
            left: 0 + "px",
            width: $(this).width() + "px"
        });
    },
    out: function(e, ui){
        var $item = ui.draggable;
        var position = $item.offset();
        var x = position.left;
        var y = position.top;
        $item.css({
            position: "absolute",
            top: y + "px",
            left: x + "px"
        });
    }
  });
});

JSFiddle Example: https://jsfiddle.net/9pk6zt5a/

The issue arises from each item calculating its position relative to the area upon attachment, causing it to snap to the top correctly. However, dragging it out changes its position to absolute to prevent interference with other items in the area.

A potential solution could involve detaching the item and reverting it to its pre-attached state, but this has not been successful thus far. Offset adjustment and position change attempts have also proved ineffective.

On another note, considering React for a more streamlined approach to this process. While unfamiliar with React, willing to explore if it offers a less frustrating solution.

Answer №1

To try undoing the action, simply drop the item back into the designated area like so:

$(function () {
    $(".draggable").draggable();
    $(".draggable").resizable();

    // Define the droppable areas for repositioning items
    $('.drag-area').droppable({
        accept: ".draggable",
        drop: function (e, ui) {
            if(!ui.draggable.parents().first().hasClass('drag-area')){
                ui.draggable.appendTo($(this)).removeAttr('style');
            }
        }
    });

    $("#snaptarget").droppable({
        accept: ".draggable",
        drop: function(e, ui) { 
            var $item = ui.draggable;
            $item.appendTo($(this)).removeAttr('style').css({
                top: ui.offset.top + "px"
            });
        },
    });
});

Check out this demo on JSFiddle!

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

Utilizing ImagesLoaded and Masonry during the subsequent AJAX request

After successfully loading the page content with an ajax call and initializing the masonry gallery using the code below, everything seems to be working fine: $(".masonry-wrapper").imagesLoaded( container, function() { setTimeout(function () { ...

Background that stretches to 100% width but only fills to the right side

UPDATE: I figured out why it wasn't working - the element with a width of 100% was nested inside a div with the class "container," removing that solved the issue! (I don't have enough reputation to answer my own question yet, just wanted to updat ...

Navigating between components using AngularJS and ExpressJS

Currently, I am embarking on a project that involves utilizing express and angularjs. To guide me through this process, I have been referring to this particular tutorial. Upon my initial attempt of running localhost:3000, I successfully loaded my index.jad ...

Drop and drag to complete the missing pieces

Here is a drag and drop fill in the blanks code I created. The challenge I'm facing is that I want users to be able to correct their mistakes by moving words to the right place after receiving points. <!DOCTYPE HTML> <html> <head&g ...

CSS a:hover not behaving as expected

So, I'm diving into creating my very first website and I'm running into a little hiccup with the "a:hover" feature in CSS. No matter what I try, the links on my page stay the same color whether hovered over or not. Here's a snippet of code ...

What is the process of utilizing PHP to validate form input within an HTML file?

I need to implement a dropdown menu item for signing in, but I am unsure how to validate the form input. Currently, I have separate pages for signing up and logging in with PHP scripts handling the validation and redirection. The issue is that I want user ...

IE is the only browser where the combination of Knockout.js and jQuery UI datepicker does not function

I utilized a knockout.js template script to construct a form that is capable of being duplicated and deleted. You can find the fiddle here. With some assistance from SE, I modified the script to incorporate a jquery-ui datepicker. The condensed version of ...

I am experiencing some difficulties with the navbar code from Bootstrap

` I recently started learning about Bootstrap and encountered an issue while trying to create a navbar. Interestingly, I wasn't even attempting to add any elements to it at that point. My main focus was to simply insert my company's or brand&apo ...

Traverse div elements using jQuery and showcase the text within them

I've got a setup like the one below. I want to use jQuery to grab each link and display its href right below it. Instead of writing code for each div individually, I'm looking for a solution that works for all divs with the 'col' class, ...

An improved method for managing asynchronous callbacks and rendering the DOM

I am currently utilizing nodemailer for sending email through reactjs. Below is the snippet of my code: constructor(props) { super(props); this.state = { fullname: "", email: "", companyName: "", phoneNumber: "", me ...

What could be causing the issue with Hindi text not displaying properly on Safari?

I'm having trouble with displaying Hindi text on my website. I tried pasting the text in a new file and it worked, so why is it not loading correctly in this case? The Hindi script is within the second span with the class word w2. "use strict"; le ...

Adjust the row based on the smallest picture

I am looking to create a photo grid using Bootstrap with images pulled from the Google Places API. The issue I am facing is that currently, the row adjusts to the height of the tallest image, but I want it to be the other way around. <div class="contai ...

Manipulating web elements by traversing through selected identifiers in LocalStorage and eliminating them from the document layout

I have a multitude of localStorage keys, including ones labeled Cart, Viewed, and Trash. There are two aspects to my query: 1) What is the most efficient way to loop through the item IDs in localStorage and add a class or data attribute to the correspond ...

Angularfire: how synchronized arrays behave

Recently, I've encountered some issues with synchronized arrays in AngularJS using AngularFire. My setup includes angularfire 1.1.3 and firebase 2.3.1. I initialized the query like this: var arr = $firebaseArray(ref.limitToFirst(5)); Initially, when ...

Div elements shifted to the right instead of appearing on a new line

Running into a formatting issue while working on my personal website. New elements are not starting on a new line but rather to the right of a div containing a picture gallery. A visual representation can be seen in this screenshot... https://i.sstatic.ne ...

modify the color of text in a row within a jquery ajax table

Is it possible to change the font color of values in a row based on a condition inside a function? Specifically, if the TotalStudent count exceeds the room capacity, can we add student information to the table with red font color? Below is my attempt using ...

How can I utilize cron to retrieve a view that includes jQuery elements?

Is there a way to schedule a cron job to execute a specific view on my Drupal website? I have a jQuery script embedded in it that I want to run every hour. I attempted the following command: php http://mysite/myview but it seems like I'm way off ta ...

Angular JS throwing error: 'ngMessages' not initialized

Here is the code snippet I am working with: // LoginCtrl.js angular.module('homeon', [ 'ngMessages' ]).controller('loginCtrl', function($rootScope, $scope, $state, $ionicLoading, dbservices, server) { //------------ ...

Turn off the warning message that says 'Type of property circularly references itself in mapped type' or find a solution to bypass it

Is there a way to disable this specific error throughout my entire project, or is there a workaround available? The error message states: "Type of property 'UID' circularly references itself in mapped type 'Partial'.ts(2615)" https:/ ...

How can we smoothly animate scrolling to the top of an element using jQuery?

I am attempting to implement a function where elements scroll to the top with animation upon being clicked. However, I am facing challenges in making this work successfully. You can view my code in action here: https://jsfiddle.net/3dqzsu2m/1/ Here is ...