HTML5 Guidelines for Web Developers

(coco) #1

280 Chapter 12—Finishing Touches:Some Global Attributes


<li ondragenter="return false;"
ondragover="return false;"
ondrop="drop(event)">❶</li>

The two events dragenter and dragover exist primarily to signal: You can drop
here! In our case, they are immediately aborted with return false. If we were to
use two callback functions, we could offer additional user feedback, for example:
You can drop here! for dragenter or Are you sure you got it right? for dragover. To
abort the event in the callback function, we do not use return false, but instead
use evt.preventDefault(). The effect is the same; it fires the drop event.
This brings us to the last task of the checklist, extracting previously set data and
implementing the game logic with the ondrop event. We again pass the DragEvent
in the argument event to the callback function drop() and then use getData() to
access the ID saved at dragstart:

var drop = function(evt) {
var id = evt.dataTransfer.getData('text');
var elemQ = questions.namedItem(id);
var elemA = evt.target;
elemA.setAttribute("data-id",id);
elemA.setAttribute("data-pop",elemQ.dataset.pop);
elemA.innerHTML = elemQ.innerHTML;
// continue game logic
};

Via the ID, we can use questions.namedItem(id) to directly access the source ob-
ject, store its number of inhabitants as a data attribute in the target object, and
use its city name as a label. The two variables elemQ and elemA are shortcuts for
the two li elements involved. Remember that Remy Sharp’s JavaScript shim for
data attributes unfortunately works only for read access, so we use the familiar
elamA.setAttribute("data-id",id) for saving the values instead of the more el-
egant elemA.dataset.id=id.
As part of the game logic, the two buttons concerned are also deactivated at
this point and visual feedback is given—in both cases via CSS classes, which we
can conveniently add via classList.add(). The additional items in the function
drop() are

elemQ.classList.add('qInactive');
elemA.classList.add('aInactive');

The corresponding formats in the CSS stylesheet are as follows:

.qInactive {
pointer-events: none;
Free download pdf