Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Drag Drop in HTML

Drag Drop in HTML

?? Drag and Drop in HTML

Drag and Drop lets users click on an element, drag it, and drop it somewhere else on the page. It’s commonly used in interactive UIs like file uploaders, sortable lists, or games.


How to Implement Drag and Drop in HTML + JavaScript

Step 1: Make an element draggable

Add the attribute draggable="true" to the HTML element.

<div id="drag1" draggable="true">Drag me!</div>

Step 2: Handle Drag Events with JavaScript

You need to listen to events like:

  • dragstart — when dragging starts

  • dragover — when dragged item is over a drop target (must prevent default to allow drop)

  • drop — when item is dropped


Basic Example

<!DOCTYPE html><html><head>  <style>    #drag1 {      width: 100px;      height: 100px;      background-color: lightblue;      cursor: move;    }    #dropzone {      width: 150px;      height: 150px;      border: 2px dashed #ccc;      margin-top: 20px;    }  </style></head><body><div id="drag1" draggable="true">Drag me!</div><div id="dropzone">Drop here</div><script>  const dragItem = document.getElementById('drag1');  const dropZone = document.getElementById('dropzone');  dragItem.addEventListener('dragstart', (e) => {    e.dataTransfer.setData('text/plain', e.target.id);  });  dropZone.addEventListener('dragover', (e) => {    e.preventDefault(); // Necessary to allow drop  });  dropZone.addEventListener('drop', (e) => {    e.preventDefault();    const id = e.dataTransfer.getData('text');    const draggedElement = document.getElementById(id);    dropZone.appendChild(draggedElement);  });</script></body></html>

Explanation

  • The draggable div (drag1) can be dragged.

  • On dragstart, we store the element’s ID in the drag data.

  • The drop zone (dropzone) listens for dragover (prevents default behavior so drop is allowed).

  • On drop, the dragged element is appended to the drop zone.


Want to build more complex drag-and-drop interfaces or use libraries like SortableJS or Dragula?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql