HTML Drag and Drop Tutorial

Implementing drag and drop functionality in HTML can be useful for various interactive web applications.

HTML Structure

  1. Start with a basic HTML structure. Create a container for draggable elements and a drop target.
<!DOCTYPE html>
  <html>
  <head>
      <title>Drag and Drop Example</title>
      <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
      <div class="container">
          <div class="draggable" draggable="true">Drag me</div>
          <div class="drop-target">Drop here</div>
      </div>
      <script src="script.js"></script>
  </body>
</html>
Drag and Drop Example
Drag me
Drop here

CSS Styles (styles.css)

  1. Style the draggable and drop target elements as desired.
  2. You can add more styling to enhance the visual presentation.
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 200px;
}

.draggable {
  width: 100px;
  height: 50px;
  background-color: #4CAF50;
  color: #fff;
  text-align: center;
  padding: 10px;
  cursor: pointer;
}

.drop-target {
  width: 100px;
  height: 50px;
  border: 2px dashed #ccc;
  text-align: center;
  padding: 20px;
}

JavaScript for Drag and Drop (script.js)

  1. Add JavaScript to handle the drag-and-drop functionality
  2. Use the dragstart, dragover, drop, and dragend events.
const draggable = document.querySelector(".draggable");
  const dropTarget = document.querySelector(".drop-target");
  
  draggable.addEventListener("dragstart", (event) => {
      event.dataTransfer.setData("text/plain", "Drag me");
  });
  
  dropTarget.addEventListener("dragover", (event) => {
      event.preventDefault();
  });
  
  dropTarget.addEventListener("drop", (event) => {
      event.preventDefault();
      const data = event.dataTransfer.getData("text/plain");
      dropTarget.textContent = data;
  });
  
  draggable.addEventListener("dragend", () => {
      draggable.textContent = "Drag me";
  });
Drag and Drop in HTML