Javascript Drag and drop example

javascript

Sure! Here’s an example of how to implement drag and drop functionality in JavaScript:

HTML:

<div id="drag">
  Drag me!
</div>
<div id="drop">
  Drop here!
</div>

CSS:

#drag {
  width: 100px;
  height: 100px;
  background-color: blue;
  color: white;
  text-align: center;
  line-height: 100px;
  cursor: move;
}

#drop {
  width: 200px;
  height: 200px;
  background-color: green;
  margin-top: 20px;
  text-align: center;
  line-height: 200px;
}

JavaScript:

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

// Add event listeners for drag start and drag end
drag.addEventListener("dragstart", dragStart);
drag.addEventListener("dragend", dragEnd);

// Functions for drag start and drag end events
function dragStart(event) {
  // Set the data to be transferred
  event.dataTransfer.setData("text/plain", event.target.id);
  // Add a class to the element being dragged
  event.target.classList.add("dragging");
}

function dragEnd(event) {
  // Remove the class from the element being dragged
  event.target.classList.remove("dragging");
}

// Get the droppable element
const drop = document.getElementById("drop");

// Add event listeners for drag over and drop
drop.addEventListener("dragover", dragOver);
drop.addEventListener("drop", dropHandler);

// Functions for drag over and drop events
function dragOver(event) {
  // Prevent the default behavior
  event.preventDefault();
}

function dropHandler(event) {
  // Prevent the default behavior
  event.preventDefault();
  // Get the data that was transferred
  const data = event.dataTransfer.getData("text/plain");
  // Move the element being dragged to the drop target
  event.target.appendChild(document.getElementById(data));
}

In this example, we have two HTML elements - a draggable element and a droppable element. We add event listeners for the dragstart, dragend, dragover, and drop events to the appropriate elements.

When the dragstart event is triggered, we set the data to be transferred using event.dataTransfer.setData(), and add a class to the element being dragged.

When the dragend event is triggered, we remove the class from the element being dragged.

When the dragover event is triggered, we prevent the default behavior using event.preventDefault().

When the drop event is triggered, we prevent the default behavior using event.preventDefault(), get the data that was transferred using event.dataTransfer.getData(), and move the element being dragged to the drop target using event.target.appendChild().