How to Implement Drag and Drop With JavaScript | Envato Tuts+

By Pro Web Design

2023-08-01 21:25:59

Drop and drop is the Holy Grail of client-side web development because it is a core feature of the graphical interfaces we use on our computers systems. Whether you use Windows, MacOS, some flavors of Linux, or even on your touch devices, drag and drop is a feature that is fundamental in the way you interact with that system. It therefore makes a lot of sense for us to include drag and drop functionality as we build web applications.

Drag and drop is a user interface (UI) interaction that allows users to click and hold on an element, drag it to a target location, and drop it there. This interaction is commonly used in various applications, including file uploads, rearranging items, creating to-do lists, and much more. In this tutorial, we’ll create a simple example of a list where you can reorder the items using drag and drop.

Setting Up the HTML

Let’s begin by setting up the HTML for our drag and drop list. Most elements are not draggable, but we can indicate to the browser that we want to make an element draggable by setting its draggable attribute to true. For example:

1

2
 lang="en">
3

4
     charset="UTF-8">
5
     name="viewport" content="width=device-width, initial-scale=1.0">
6
    </span>Tuts+ - Drag and Drop<span style="color: #f4bf75">
7
    
10

11

12
    

Drag and Drop

13
     class="list-container">
14
         class="draggable-list">
15
             draggable="true">Item 1
16
             draggable="true">Item 2
17
             draggable="true">Item 3
18
             draggable="true">Item 4
19
             draggable="true">Item 5
20
        
21
    
22
    
23

24

This is the structure of our HTML document, but pay special attention to the

  • elements. We want to enable the reordering of
  • elements by dragging and dropping them to different positions in the list. Therefore, we need to set their draggable attribute to true. Otherwise, the browser will not allow us to drag the elements. Remember that you don't always have to set an element's draggable attribute directly in the HTML; it can also be done programmatically if your situation requires it.

    Styling the Elements

    It's not necessary to style our elements to make drag and drop work, but it does make our elements easier to work with. It also gives us an opportunity to provide visual cues to our users. Add the following CSS to the