Placing a moveable object in a designated spot for dropping at the desired location

I've been attempting to clone and drop a draggable object at the exact position within a droppable area where the drop event takes place. While I have come across examples online that demonstrate appending draggables to droppables, they all tend to relocate the draggable item to a predetermined location within the droppable upon initial drop.

Here's an illustration of this behavior: - http://jsfiddle.net/scaillerie/njYqA/

//JavaScript snippet from the provided jsfiddle
jQuery(function() {
  jQuery(".component").draggable({
      helper: function() {
          return jQuery(this).clone().appendTo('body').css({
              'zIndex': 5
          });
      },
      cursor: 'move',
      containment: "document"
  });

  jQuery('.ui-layout-center').droppable({
      activeClass: 'ui-state-hover',
      accept: '.component',
      drop: function(event, ui) {
          if (!ui.draggable.hasClass("dropped"))
              jQuery(this).append(jQuery(ui.draggable).clone().addClass("dropped").draggable());
          }
      });
  });

Is there any way to ensure that the draggable element remains positioned at the exact coordinates of the drop event?

Answer №1

To ensure proper functionality, it is crucial to specify the coordinates of the cloned element when it is dropped:

drop: function(event, ui) { if (!ui.draggable.hasClass("dropped"))

        var clone=jQuery(ui.draggable).clone().addClass("dropped").draggable();
        clone.css('left',ui.position.left);    
        clone.css('top',ui.position.top);

        jQuery(this).append(clone);
    }
});

Additionally, make sure to set the position to absolute using CSS for the cloned components:

.ui-layout-center .component {
   position:absolute !important;   
}

You can see a working example here: http://jsfiddle.net/o2epq7p2/

Answer №2

Altered the code by utilizing appendTo() and adjusting the offset

jQuery(function() {
    jQuery(".component").draggable({
        //  utilize a helper-clone that is appended to 'body' so it is not 'contained' by a pane
        helper: function() {
            return jQuery(this).clone().appendTo('body').css({
                'zIndex': 5
            });
        },
        cursor: 'move',
        containment: "document"
    });

    jQuery('.ui-layout-center').droppable({
        activeClass: 'ui-state-hover',
        accept: '.component',
        drop: function(event, ui) {
            var _this = jQuery(this);
            if (!ui.draggable.hasClass("dropped")) {
                var cloned = jQuery(ui.draggable).clone().addClass("dropped").draggable();
                jQuery(cloned).appendTo(this).offset({
                    top : ui.offset.top,
                    left: ui.offset.left
                });
            }  
        }
    });
});

Answer №3

ui within the drop function includes the absolute position of the dragged element on the page. To align these values relative to the drop target and accurately position the cloned element within the drop target, some transformations are necessary.

    drop: function(e, ui) {
        if (!ui.draggable.hasClass("dropped")) {
            var parentOffset = jQuery('.ui-layout-center').offset();
            var dropped = jQuery(ui.draggable).clone().addClass("dropped").draggable();
            dropped.css('left', (ui.position.left  - parentOffset.left) +'px');
            dropped.css('top', (ui.position.top - parentOffset.top) +'px');

            jQuery(this).append(dropped);
        }
    }

http://jsfiddle.net/3Lnqocf3/

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

Issue with passing parameters to function when calling NodeJS Mocha

I have the following function: export function ensurePathFormat(filePath: string, test = false) { console.log(test); if (!filePath || filePath === '') { if (test) { throw new Error('Invalid or empty path provided'); } ...

Having trouble transferring data between Vue.JS components

Wondering how to pass data from the parent component (Home route) to the child component (playlist route) using props? Encountering a "TypeError: Cannot read property 'length' of undefined" error in the child component? These two components are c ...

Attempting to utilize express-load in conjunction with express 4

As a beginner in NodeJS, I encountered a problem with my code. Let me show you the issue. I am trying to load the application in the MVC pattern using express-load, but I am facing an error when defining the load order. Here is the important part of app. ...

Error: Unable to retrieve data through Ajax request

$(document).ready(function(){ /* Fetching Data from TTC for Union Station */ $.getJSON("http://myttc.ca/Union_station.json?callback=?", function(data){ if (routes.length > 0) { // Display the stop details with departur ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...

Importing usernames and passwords from a .txt file with Javascript

I'm in the process of creating a website that includes a login feature. The usernames and passwords are currently stored within the website files as .txt documents. I am aware that this method is not secure, but for the purpose of this project, I want ...

"Troubleshoot the issue of a Meteor (Node.js) service becoming unresponsive

Currently running a Meteor (Node.js) app in production that is experiencing unexplained hang-ups. Despite implementing various log statements, I have pinpointed the issue to a specific method where the server consistently freezes. Are there any tools beyo ...

Retrieving the first five rows from a table with data entries

My task involves working with a table named mytbl, which contains 100 rows. I need to extract only the first five rows when a user clicks on "Show Top Five." Although I attempted the following code, the alert message returned 'empty': var $upda ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

Web Security Vulnerability: Cross Site Scripting Detected

In our code, we are aiming to prevent XSS (Cross Site Scripting) attacks. However, the solution may involve a combination of JS (JavaScript) and HTML escaping, which could prove to be quite challenging. Below is a snippet that closely resembles our code: ...

The margin 0 auto feature is ineffective, and instead, the target is activated upon the page's initial loading

As a beginner in CSS, I am encountering some issues with the HTML page of my application. I am currently working on an app and aiming to create a login view where the login form appears either after a voice command or button click. I am facing two main pro ...

Utilize npm node to dynamically adjust screen resolution

Currently developing a game using electron. I'm experiencing FPS drops when running it in full-screen mode. To improve the game's performance, I need to change the screen resolution programmatically. My current resolution is 1280x800, but I would ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Update the class information using jQuery after performing an action and serialize the button's ID for AJAX requests

I'm facing an issue with two buttons on my page: <td> <button id="1" class="green-button">Publish</button> <button id="1" class="yellow-button">Delete</button> </td> The green-button and red-button have different ...

Tips for aligning images inside tab content areas

While using an "accordion" jQuery to show a contact list, I have encountered a challenge that may seem simple to someone experienced in this. Here is the code snippet: <!doctype html> <html lang="en> ... (Code continues) I am looking to add ...

Implementing JavaScript to display specific content when a list is devoid of any items

Currently, I am in the process of developing a basic contact list web application where the contacts are listed within li elements. My aim is to adjust the visibility of the text in the p#no-contacts element based on whether the containing ul has any child ...

Update the href attribute with values from the form fields

My current project involves creating a form with 5 input fields: Service type Number of days Number of children Number of adults I want to dynamically change the value of a button based on these variables using JavaScript. Here is my code so far: JS ...

Disappearing Into the Background Excluding Specific Divs

I have a dilemma with fading in and out a background image using jQuery fadeIn and fadeOut. The issue arises because my wrapper div contains elements such as sidebar and navigation that are positioned absolutely within the wrapper div, causing them to also ...

Error: Unable to retrieve the "error" property as the data is not defined

Encountered a title error and struggling to fix it :(. Attempting to retrieve data from a signup page, here is the snippet of my JavaScript code: const SignupComponent = () => { const [values, setValues] = useState({ name: 'ryan', emai ...

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...