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

Exploring the Contrast between window.location.href and top.location.href

I'm curious about the distinction between window.location.href and top.location.href. Can anyone explain this to me? Furthermore, I'd like to know when it's appropriate to use each one. Which option is more suitable for redirection after a ...

Customizing Slider knob design

I'm trying to customize the look of the JQueryUI slider by changing the handle images, but I can't seem to find any information on how to do it. Even the JQuery Themeroller doesn't offer an option for changing handle images. Does anyone have ...

Creating connections between variables and elements in nested ngRepeats in Angular

I've been facing a challenge with my app where I need to update the comments section whenever a comment is added, edited, or deleted without having to refresh the page. I am using ngResource to handle queries for both articles and comments (e.g. $scop ...

Real-time File Updates Display with Node.js and Express.js

Seeking guidance on whether there is a Node module available to utilize the Express module for displaying real-time updates in the browser using data from a file. I have a regularly updated .csv file and I am looking to showcase these updates instantly on ...

Adding options for a select tag from JavaScript can be accomplished by using the DOM manipulation methods

I am working on a form that includes drop-down menus. The options for the select tag need to change dynamically based on the id value. For instance, if the id is 1, the select tag options should be cat and dog. If the id is 2, the options should be apple ...

"Improve your Angular ngrx workflow by utilizing the sandbox pattern to steer clear of

Currently, I'm trying to determine whether my implementation of the ngrx and sandbox pattern is effective. Here's the issue I'm facing: getFiles(userId: number, companyId: number) { this.fileService.getFiles(userId, companyId).subscribe(re ...

Update the configurable product process for the custom attribute 'delivery_time' in Magento 1.9.2

I am currently using Magento 1.9.2.4 (1.9.2.3 in my Testpage) and I have a few configurable products with multiple options. Each product (child of the configurable one) has a different delivery time. To achieve this, I created an attribute called "delivery ...

Styling used on the ofx.com website

I am attempting to recreate the CSS effects used on ofx.com, which includes a picture of London and a grey box with text. However, my version is not working properly. I am unsure of what might be missing in my code. Here is the snippet: .generic-hero-bl ...

Using middleware in Express to handle GET requests

Can the request object sent to any route be accessed globally in Express, without having to explicitly access it in a .get method or similar? ...

Slider-activated Pie Chart Controller

I have successfully created a pie chart using highchart and javascript, allowing me to adjust each slice individually using a slider. However, I am facing an issue where I want the maximum value of the pie to be 100%, with the other sliders contributing to ...

Finding the next div by its ID using jQuery

Currently, the jQuery code provided only allows navigation from the Sport section to the Entertainment section. Is there a way to create a script that allows navigation between any div sections with just one piece of code? <div id="topBar"> &l ...

Trouble arises when attempting to incorporate the Restangular dependency with Angular using browserify

I've been using browserify to manage my angular dependencies successfully, however, when I try to add restangular I encounter an error: "Uncaught Error [$injector:modulerr]". Here's a glimpse of my package.json: "browser": { "angular": "./ ...

What is the best way to conduct tests on React components' methods and ensure they are integrated into my Istanbul coverage report

Is there a way to test the methods of react components and include them in my Istanbul test coverage? Edit: I'm using enzyme. Just wanted to mention that. Take, for instance, this component: class SearchFormContainer extends Component { static h ...

Utilize Jquery to calculate the product of the number inputted into the field

Seeking guidance on multiplying the annual liters (#save-lt) by the average fuel price (#usd). The calculation for what you save per year in liters is functioning correctly. Any suggestions? I believe a variable may be necessary. As a beginner in jquery, a ...

Can the ::before selector be used in HTML emails?

Hey there, I have a question that might sound silly but I'm having trouble finding an answer online. My issue is with styling the bullet point before a list item in an HTML email. All I want to do is change the bullet point to a square and give it a ...

Troubleshooting problem with Materialize CSS in UI router

Incorporating Materialize CSS along with Angular's ui.router for state management and HTML rendering has led to a challenge. Specifically, the Materialize Select component is not initialized upon state changes since Materialize components are typicall ...

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

Click on the link to return to the previous page on the website

As I work on customizing a Tumblr theme, I find myself facing a few challenges. One such issue is my desire to include a link on post pages that directs users back to the previous page, similar to what is shown in this image: picture1 I have attempted var ...

Compiling with GatsbyJs throws an abrupt token error with 'if' being an unexpected token

I am working on a code snippet in GatsbyJS where I am extracting data from a StaticQuery using GraphQL and then rendering a component. The challenge I am facing is to conditionally check if a specific sub-object exists within the data object, and if it doe ...

Working with JSON data in javascript

While trying to parse JSON data from a server, I came across a strange issue. The data consists of rows of data - essentially a list of lists - and it looks something like this: [[1,2,3],[4,5,6],[7,8,9]] When viewing the JSON data in FF (using Firebug), ...