HTML5 Guidelines for Web Developers

(coco) #1
12.5 Drag and Drop with the “draggable” Attribute 279


  1. Deciding where the dragged element can be dropped

  2. Extracting the data as soon as the user ends the drag-and-drop operation
    on a valid target object


We can fulfill the first task with the global draggable attribute. Via draggable=true
it marks the relevant element as a candidate for dragging to another position.
Two HTML elements are by default defined as draggable: the img element and
the a element, provided it has an href attribute, which made it possible previ-
ously to drag links or images on the desktop and save them easily. If we wanted
to prevent drag and drop in these elements, we could use draggable=false.


To prepare an entry in the city list for drag and drop, we first need to add the
draggable attribute and set it to true:


  • Brussels

  • Drag-and-drop operations are not an end unto themselves but a means to an
    end: Their purpose is to transfer information from one place to another. Which
    information this is must be determined at the start of the drag operation in ques-
    tion, which is why we add a dragstart event handler to each item in our city list.
    It calls the callback function startDrag() and passes it the so-called DragEvent in
    the argument event:


    <li id=be draggable=true
    ondragstart="startDrag(event)">Brussels


    This DragEvent plays a central role in drag and drop, because its readonly attri-
    bute dataTransfer gives us access to the DataTransfer interface of the drag-and-
    drop API, where all necessary methods and attributes of drag and drop are avail-
    able. One of these methods is setData(format, data). This determines which
    data is to be dragged along in the background when dragging from A to B. In our
    case, it is the ID in the format text. With this we will later be able to access the
    original data:


    var dragStart = function(evt) {
    evt.dataTransfer.setData('text',evt.target.id);
    };


    From this point on, the list item can be dragged—where we will drop it remains
    open. It would be helpful to have a droppable attribute available in parallel to the
    draggable attribute, but this is not the case, which is why we require no less than
    three events for successful dropping: dragenter, dragover, and drop. Strangely
    enough, two of them must be aborted in order for the third and most important
    event to be fired. The HTML code for one of the list items on the left of the game,
    where the cities are arranged, shows us which ones they are

    Free download pdf