JAVASCRIPT

Implement Drag and Drop Functionality

Learn to create interactive drag and drop elements using native JavaScript DOM events like dragstart, dragover, and drop for enhanced user interfaces.

document.addEventListener('DOMContentLoaded', () => {
  const draggableItems = document.querySelectorAll('.draggable');
  const dropZones = document.querySelectorAll('.dropzone');

  let draggedItem = null;

  draggableItems.forEach(item => {
    item.setAttribute('draggable', true);
    item.addEventListener('dragstart', (e) => {
      draggedItem = item;
      setTimeout(() => {
        item.style.opacity = '0.5';
      }, 0);
    });

    item.addEventListener('dragend', () => {
      draggedItem.style.opacity = '1';
      draggedItem = null;
    });
  });

  dropZones.forEach(zone => {
    zone.addEventListener('dragover', (e) => {
      e.preventDefault(); // Allows the drop
      zone.style.backgroundColor = '#f0f0f0';
    });

    zone.addEventListener('dragleave', () => {
      zone.style.backgroundColor = '';
    });

    zone.addEventListener('drop', (e) => {
      e.preventDefault();
      if (draggedItem) {
        zone.appendChild(draggedItem); // Move the item to the dropzone
      }
      zone.style.backgroundColor = '';
    });
  });
});
/*
HTML structure example:
<style>
  .draggable { border: 1px solid blue; padding: 10px; margin: 5px; background-color: lightblue; cursor: grab; }
  .dropzone { border: 2px dashed gray; padding: 20px; min-height: 100px; margin: 10px; }
</style>
<div class="dropzone">Drop Zone 1
  <div class="draggable">Draggable Item 1</div>
</div>
<div class="dropzone">Drop Zone 2</div>
*/
How it works: This snippet demonstrates how to implement basic drag and drop functionality. It identifies draggable elements and drop zones, then attaches event listeners for 'dragstart', 'dragend', 'dragover', 'dragleave', and 'drop'. When an item is dragged, its reference is stored. 'dragover' prevents the default browser behavior, enabling the drop, while 'drop' appends the dragged item to the target drop zone, creating an interactive user experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs