"Mastering Object Manipulation: A Guide to Dragging, Dropping, and Cloning

Having some trouble with cloning an object using interact.js. Drag and drop works fine, but I can't figure out how to clone the objects.

Below is the drag and drop code. Can anyone help me modify it to include object cloning?

#drag-1, #drag-2 {
  width: 20%;
  height: 10%;
  min-height: 6.5em;
  margin: 10%;

  background-color: #29e;
  color: white;

  border-radius: 0.75em;
  padding: 4%;

  -webkit-transform: translate(0px, 0px);
          transform: translate(0px, 0px);
}

#drag-me::before {
  content: "#" attr(id);
  font-weight: bold;
}
    top:35px; left:40px; width:50px; height:50px;
    z-index:99; background-color:#44ebfa;
}
<html>
<head>
<title>test 1 </title>
<!--<script type="text/javascript" src="d3-js/d3.min.js"></script>-->
<script type="text/javascript" src="www.googledrive.com/host/0B4A7r4wXVSe-SDdVdlNtbnhFZ2s"></script>
<link rel="stylesheet" type="text/css" href="test1_css1.css">
</head>
<body>

<script>


// target elements with the "draggable" class
interact('.draggable')
  .draggable({
    // enable inertial throwing
    inertia: true,
    // keep the element within the area of it's parent
    restrict: {
      restriction: "parent",
      endOnly: true,
      elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    },

    // call this function on every dragmove event
    onmove: dragMoveListener,
    // call this function on every dragend event
    onend: function (event) {
      var textEl = event.target.querySelector('p');

      textEl && (textEl.textContent =
        'moved a distance of '
        + (Math.sqrt(event.dx * event.dx +
                     event.dy * event.dy)|0) + 'px');
    }
  });

  function dragMoveListener (event) {
    var target = event.target,
        // keep the dragged position in the data-x/data-y attributes
        x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
        y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

    // translate the element
    target.style.webkitTransform =
    target.style.transform =
      'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
  }

  // this is used later in the resizing demo
  window.dragMoveListener = dragMoveListener;

</script>

<div id="drag-1" class="draggable">
  <p> You can drag one element </p>
</div>
<div id="drag-2" class="draggable">
<p> with each pointer </p>
</div>


</body>
</html>

Answer №1

Check out this code snippet

interact('.draggable').draggable({
    inertia: true,
    restrict: {
      restriction: "#visualizer-panel",
      endOnly: true,
      elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    },
    onmove: function (event) {
      var target = event.target;   
      var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
      var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

      target.style.webkitTransform =
      target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';

      target.setAttribute('data-x', x);
      target.setAttribute('data-y', y);
    },
    onend: function(event) {
        console.log(event);
    }
}).on('move', function (event) {
var interaction = event.interaction;
if (interaction.pointerIsDown && !interaction.interacting() && event.currentTarget.getAttribute('clonable') != 'false') {
  var original = event.currentTarget;
  var clone = event.currentTarget.cloneNode(true);
  var x = clone.offsetLeft;
  var y = clone.offsetTop;
  clone.setAttribute('clonable','false');
  clone.style.position = "absolute";
  clone.style.left = original.offsetLeft+"px";
  clone.style.top = original.offsetTop+"px";
  original.parentElement.appendChild(clone);
  interaction.start({ name: 'drag' },event.interactable,clone);
}
});

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

Reloading the webpage while simultaneously shutting down the modal popup with jQuery

My Issue : One of my challenges involves a modal form that appears when I click on a submit button. This form allows users to input information and request a demo from an organization. The data entered into the form is then stored in a MySQL database usin ...

Exploring the navigation options within React Native's DrawerLayoutAndroid component

My goal is to seamlessly navigate between different views using the Drawer layout. It would be ideal if I could achieve this directly in the navBar without having to create a separate toolbar for each view https://i.sstatic.net/joOeB.png Currently, clicki ...

Creating a Step-by-Step Sequential Slider

How can I create a slider with 3 specific positions - 0, 50, and 100, while also implementing restrictions that prompt a confirmation message for each position? <input type='range'> ...

Steps for removing an element from an array after unchecking a checkbox:

My issue involves handling multiple locations - when a particular location is checked, it gets added to an array. However, I am unable to remove it from the array when the checkbox is unchecked. handleChange(e){ if(e.target.checked){ let selec ...

What causes a statically generated page to appear without any style when transmitted to the client?

After setting up the Next.js official boilerplate with npx create-next-app and opening it in the browser, I observed that the static HTML document lacks styling: https://i.stack.imgur.com/mna6K.png I am concerned about potential FOUC issues. How can I en ...

What is causing the constant failure of the httpr.send() method?

I had a similar code running before, but unfortunately, I seem to have lost it. Despite trying different approaches, the PHP code just won't execute. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8& ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

Navigate through intricate JSON structure

Struggling with a highly complex JSON object, I am trying to list out all the properties and keys exactly as they are. While I have grasped the concept, I am having trouble with the execution. Every time the object contains another object, I need to call ...

Is there a way to initiate the server only after webpack has finished bundling all of the bundles

"scripts": { "start": "node server.js", "build": "webpack" }, Is there a way to execute both npm run build and npm start with a single command? "scripts": { "start": " ...

Attempting to extract a parameter from a URL and pass it as an argument to a function for the purpose of locating objects based on

I am trying to retrieve data from a URL http://localhost:3000/share/user=sampleuser to display objects with an author value that matches the one in the URL. However, I encountered an error when attempting to call a function that extracts the value from t ...

The jQuery extension for XDomainRequest in the $.ajax function called onprogress is

Summary: I am trying to make this compatible with this: Detailed Explanation: My goal is to develop a jQuery extension that introduces a progress method to the $.ajax object and works seamlessly with IE8 & IE9's XDomainRequest object. Currently, I ...

Sending numerous POST attributes utilizing identical parameter name

Currently, I am facing a situation that requires me to send POST parameters with the same name. Can anyone provide guidance on how this can be accomplished? I have successfully handled a similar scenario with a GET request by constructing the URL and appen ...

Integrating chat functionality with a structured data format

Considering creating a collaborative communication platform, I am contemplating whether to develop a comprehensive application in JavaScript with MVC architecture or utilize it solely for managing message delivery using Node.js and socketIO. Would it be m ...

Mastering SVG Path Coordinates using Pure JavaScript

Is it possible to target and manipulate just one of the coordinate numbers within an SVG path's 'd' attribute using JavaScript? For example, how can I access the number 0 in "L25 0" to increment it for animating the path? function NavHalf ...

Achieve full height for div without causing it to expand (utilize scrollbar for overflow)

I am looking to achieve a specific layout for my webpage, as shown in the image below: The layout depicted in the image above is created using the following HTML and bootstrap classes: <div className="ContentWrapper d-flex mh-100 flex-row h-10 ...

Struggling to click on a dynamic link before it times out

Can someone help me with a puzzling issue I can't seem to solve? I am trying to achieve the following: Whenever a link is clicked (for example: mysite.com/blog/blog-article.html), I want to save the href of that link to a variable. Then, in JavaScri ...

When the screen size changes, the Bootstrap 4 h-100 column does not stack correctly

I've encountered an issue with Bootstrap 4 while utilizing the h-50 and h-100 helper classes along with rows incorporating columns of different breakpoints. Consider the following scenario : <style> html,body { height: 100%; } ...

When the if-else statement is executed, it showcases two strings:

Learning Experience: Unveiling My Lack of Cleverness Update: It appears that utilizing PHP in my current setup is not possible. As a result, I'll take some time to contemplate while banging my head against a wall. Despite that, thank you all for your ...

incorporating the same model into the scene multiple times

Currently, I am loading a single model multiple times using the following code: var loader = new THREE.JSONLoader(); loader.load(model, load_func); The function load_func is responsible for creating a mesh and adding it to the scene: var mesh = new THRE ...

What is the method for creating a function that calculates the perimeter of a rectangle having a width of 5 and a height of 8?

I'm struggling with my current attempt. I can't figure out where to input the values 5 and 8 for width and height. Any assistance or advice would be greatly appreciated. function rectPerimeter(width, height) { return 2 * width + 2 * height; } ...