Drag and Drop elements between two papers using Joint.js

I am facing a challenge with synchronizing the offset of a dragged element with the cursor position while implementing drag and drop between two papers on my HTML page. My limited experience with CSS might be causing issues with element positioning.

Here is the use case:

The user clicks on an element from paper 2, starts dragging it, and moves to paper 1. Upon releasing the mouse button, a clone of that element is added to paper 1 at the cursor's position in paper 1.

My strategy to address this issue involves:

When the user clicks on mousedown:

1. Dynamically create a div

2. Create a third paper (called "flypaper") within the new div, make a copy of the element to be cloned, and add it to "flypaper"

3. Set up a mousemove listener to move the div containing "flypaper" along with the mouse

4. Attach a mouseup event that adds a clone of the element to "paper2" when the user releases the button

5. Clean up the "flypaper" div and events

<body>
<div id="paper" class="paper" style="border-style: solid;border-width: 5px;width:600px"></div>
<div id="paper2" class="paper" style="border-style: solid;border-width: 5px;width:600px;display:inline-block" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<script>
    // JavaScript code for drag and drop functionality goes here...
</script>
</body>

Answer №1

I encountered a similar issue (and faced resistance from clients unwilling to pay for rappid which provides this functionality for jointjs). Here is a helpful snippet that might assist others (details below).

The steps align with your observations:
1. Generate a div dynamically.
2. Establish a third paper, referred to as "flypaper," within the new div. Duplicate the desired element and append it to "flypaper."
3. Implement a mousemove listener to move the div containing "flypaper" in sync with the mouse movement.
4. Incorporate a mouseup event that places a clone of the element onto "paper2" upon releasing the mouse button.
5. Tidy up the "flypaper" div along with associated events.

The resolution involved utilizing cellView.model.clone() for adding the appropriate element, followed by calculations leveraging $.offset, $.width(), and $.height() to determine the accurate flying paper position and confirm if the drop event happened on the target paper.

Access on codepen

<body>
<div id="paper" class="paper" style="border-style: solid;border-width: 5px;width:600px"></div>
<div id="paper2" class="paper" style="border-style: solid;border-width: 5px;width:600px;display:inline-block"></div>
<script>
    // Canvas where shapes are dropped
    var graph = new joint.dia.Graph,
      paper = new joint.dia.Paper({
        el: $('#paper'),
        model: graph
      });

    // Canvas providing shapes
    var stencilGraph = new joint.dia.Graph,
      stencilPaper = new joint.dia.Paper({
        el: $('#stencil'),
        height: 60,
        model: stencilGraph,
        interactive: false
      });

    var r1 = new joint.shapes.basic.Rect({
      position: {
        x: 10,
        y: 10
      },
      size: {
        width: 100,
        height: 40
      },
      attrs: {
        text: {
          text: 'Rect1'
        }
      }
    });
    var r2 = new joint.shapes.basic.Rect({
      position: {
        x: 120,
        y: 10
      },
      size: {
        width: 100,
        height: 40
      },
      attrs: {
        text: {
          text: 'Rect2'
        }
      }
    });
    stencilGraph.addCells([r1, r2]);

    stencilPaper.on('cell:pointerdown', function(cellView, e, x, y) {
      $('body').append('<div id="flyPaper" style="position:fixed;z-index:100;opacity:.7;pointer-event:none;"></div>');
      var flyGraph = new joint.dia.Graph,
        flyPaper = new joint.dia.Paper({
          el: $('#flyPaper'),
          model: flyGraph,
          interactive: false
        }),
        flyShape = cellView.model.clone(),
        pos = cellView.model.position(),
        offset = {
          x: x - pos.x,
          y: y - pos.y
        };

      flyShape.position(0, 0);
      flyGraph.addCell(flyShape);
      $("#flyPaper").offset({
        left: e.pageX - offset.x,
        top: e.pageY - offset.y
      });
      $('body').on('mousemove.fly', function(e) {
        $("#flyPaper").offset({
          left: e.pageX - offset.x,
          top: e.pageY - offset.y
        });
      });
      $('body').on('mouseup.fly', function(e) {
        var x = e.pageX,
          y = e.pageY,
          target = paper.$el.offset();

        // Dropped over paper ?
        if (x > target.left && x < target.left + paper.$el.width() && y > target.top && y < target.top + paper.$el.height()) {
          var s = flyShape.clone();
          s.position(x - target.left - offset.x, y - target.top - offset.y);
          graph.addCell(s);
        }
        $('body').off('mousemove.fly').off('mouseup.fly');
        flyShape.remove();
        $('#flyPaper').remove();
      });
    });
</script>
</body>

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

JavaScript code that triggers when a checkbox is not selected

I'm attempting to dynamically add an input field when a checkbox is clicked, with the intention of having the checkbox already checked by default. However, I am encountering an issue where the checkbox remains unchecked even after the input field is d ...

Obtain the current user's Windows username without relying on the ActiveX object

Is there a way to retrieve a client's Windows username in ASP.NET when hosted on a remote server without using an ActiveX object? I tried the following code: Response.Write("HttpContext.Current.Request.LogonUserIdentity.Name " & HttpContext.Cur ...

Creating a new event using 'build' versus creating a custom event with the same name 'build'

While browsing the MDN page on Creating and Triggering Events, I came across an example showcasing the creation of events using Event or CustomEvent. The article mentions that CustomEvent allows for custom details, but doesn't elaborate much on the di ...

Is there a way to alter the timestamp on comments in a React Native app, similar to Instagram's functionality, using dayjs?

I am currently working on a project using react native in combination with dayjs library. My goal is to compare the timestamp of when a comment was written with the current time, and then display this compared time using console.log() with the help of day ...

How can I hide a root layout component in specific nested routes within the app directory of Next.js?

Is there a way to prevent rootlayout from being wrapped around dashboardlayout? Explore the latest documentation for Next.js version v13: https://i.sstatic.net/M0G1W.png Take a look at my file structure: https://i.sstatic.net/nVsUX.png I considered usi ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

The Colorbox feature showcases images in their binary data format

I'm currently experimenting with using Colorbox to enhance a website that is being built with Backbone.js. Within my code, I have a straightforward image tag set up like this: <a class="gallery" href="/document/123"><img class="attachment-pr ...

The challenge of incorporating Laravel, Vue, and JavaScript into a Blade template

It may seem like a silly question, but I am struggling to find a solution. My goal is to load a Vue component and JS file into a blade view. When I include the following: <script src="{{ asset('js/app.js') }}"></script> <script sr ...

ng-grid cell onclick callback

Currently, I am working with ng-grid and am attempting to define a callback function for when a cell is clicked. During this callback, it is crucial for me to identify the specific row and column of the cell that was clicked. Upon exploring various options ...

Passing data through multiple levels in Angular

Imagine you have a main component called A with a variable x inside it that you want to pass to a child component B. Using the @Input annotation makes this task simple. But what if component B has its own child component C? How can we successfully pass t ...

Automatically fill out form fields by selecting data from a spreadsheet

I successfully created a web application using Google Apps Script (GAS) that sends data on submission to Spreadsheet A. Furthermore, I have implemented a select option that dynamically fetches data from another spreadsheet B ("xxx") in column A. Below is ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

Utilize JavaScript to compute and implement a deeper shade of background color

To dynamically apply darker shades of background using JavaScript, I have devised the following code. .event-list .bg{ background:#eee; padding:5px; } .grid .event-list:first-child .bg{ background: #2aac97 } .grid .event-list:nth-child(2) .bg{ backgrou ...

Customize the appearance of the "Collapse" component in the antd react library by overriding the default styles

Incorporating JSX syntax with *.css for my react component. Displayed below is the jsx code for the antd collapse section. <Collapse defaultActiveKey={["1"]} expandIconPosition="right" > <Panel header="This is p ...

Validating date parameter in Wiremock request - How to ensure dynamic date matching during testing?

Looking for some assistance in verifying that the date in a request is exactly Today. I've tried various methods from the documentation, but haven't achieved the desired outcome yet. Calling out to any helpful souls who can guide a junior QA thro ...

Retrieve the image description using the file_picker_callback and image uploader in Tinymce

TL:DR I am attempting to retrieve the value of the image_description field using JavaScript to include it in my post XHR request Original query: I am utilizing the file_picker_callback type image I have enabled the image_description input field in my ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...

Generate CANNON.RigidBody using either a THREE.Mesh or THREE.Geometry object

For my project, I am using a THREE.JSONLoader to create a THREE.Mesh object as shown below: // Creating a castle. loader.load('/Meshes/CastleTower.js', function(geometry, materials) { var tmp_material = new THREE.MeshLambertMaterial(); T ...