Implement Drag and Drop Using jQuery UI

Implementing a drag-and-drop interface with jQuery UI is a straightforward process that involves linking the necessary libraries, defining draggable and droppable elements in HTML, and initializing them with jQuery UI methods. This guide covers the essential steps to configure the basic setup, bind drag and drop events, and customize behavior using built-in options like revert, containment, and visual feedback.

1. Include Required Libraries

To use jQuery UI, include both the jQuery library and the jQuery UI library (along with its CSS stylesheet) in the <head> of your HTML document:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

2. Set Up the HTML and CSS

Define the element you want to drag and the target container where the item should be dropped.

<div id="draggable" class="box">Drag me</div>
<div id="droppable" class="drop-zone">Drop here</div>

Add basic styling to give the elements visible dimensions:

.box {
  width: 100px;
  height: 100px;
  background-color: #3498db;
  color: #fff;
  line-height: 100px;
  text-align: center;
  cursor: grab;
}

.drop-zone {
  width: 200px;
  height: 200px;
  background-color: #ecf0f1;
  border: 2px dashed #bdc3c7;
  line-height: 200px;
  text-align: center;
  margin-top: 20px;
}

.drop-zone.highlight {
  background-color: #2ecc71;
  color: #fff;
  border-color: #27ae60;
}

3. Initialize Draggable and Droppable Elements

Use the .draggable() method to make an element movable, and the .droppable() method to define the target area. Handle the drop event to trigger actions when the draggable item is released over the drop zone.

$(document).ready(function() {
  // Initialize the draggable element
  $("#draggable").draggable({
    revert: "invalid" // Returns the element to its original position if not dropped in a valid target
  });

  // Initialize the droppable target
  $("#droppable").droppable({
    accept: "#draggable", // Specify which elements can be dropped
    hoverClass: "highlight", // CSS class added when a valid draggable hovers over it
    drop: function(event, ui) {
      $(this)
        .addClass("highlight")
        .text("Dropped successfully!");
    }
  });
});

4. Common Configuration Options

  • revert: Set to true or "invalid" to snap the draggable item back to its starting coordinates when dropped outside of an accepted droppable area.
  • containment: Restricts dragging within the bounds of a specified DOM element, selector, or "parent".
  • axis: Constrains dragging along either the horizontal ("x") or vertical ("y") plane.
  • accept: A selector string in the .droppable() config determining which specific draggables can trigger drop events.