make an element draggable and droppable between two other elements in javascript

To make an element draggable and droppable between two other elements in JavaScript, you can use the HTML5 drag-and-drop API.

First, you need to add the draggable attribute to the element you want to make draggable. For example, if you have an element with ID "drag", you can set the draggable attribute like this:

<div id="drag" draggable="true">Drag me</div>
46 chars
2 lines

Next, you need to add event listeners for the drag-and-drop events. You can use the ondragstart event to set the data that will be dragged, and the ondragover and ondrop events to handle the drop.

Here's an example of how to implement drag-and-drop between two other elements with IDs "dropzone1" and "dropzone2":

// Get the draggable element
var dragElem = document.getElementById("drag");

dragElem.addEventListener("dragstart", function(event) {
  // Set the data that will be dragged
  event.dataTransfer.setData("text/plain", event.target.id);
});

// Get the drop zones
var dropZone1 = document.getElementById("dropzone1");
var dropZone2 = document.getElementById("dropzone2");

// Add event listeners for the drop zones
dropZone1.addEventListener("dragover", function(event) {
  event.preventDefault(); // Allow drop
});

dropZone1.addEventListener("drop", function(event) {
  event.preventDefault(); // Prevent default behavior
  var data = event.dataTransfer.getData("text/plain");
  var draggedElem = document.getElementById(data);
  dropZone1.insertBefore(draggedElem, dropZone1.firstChild);
});

dropZone2.addEventListener("dragover", function(event) {
  event.preventDefault(); // Allow drop
});

dropZone2.addEventListener("drop", function(event) {
  event.preventDefault(); // Prevent default behavior
  var data = event.dataTransfer.getData("text/plain");
  var draggedElem = document.getElementById(data);
  dropZone2.appendChild(draggedElem);
});
1151 chars
35 lines

In this example, the ondragstart event sets the data that will be dragged, and the ondragover and ondrop events handle the drop in each of the two drop zones.

The event.preventDefault() method is called to allow the element to be dropped in the drop zone and to prevent the default behavior of the browser.

The event.dataTransfer.getData() method is called to get the ID of the dragged element, which is then inserted into the drop zone.

gistlibby LogSnag