Lesson 1: Dragging and dropping CHAPTER 13 515
$('#favoriteCars').on('drop', dropItem);
});
function dragging(e) {
var val = e.target.getAttribute('data-value');
e.dataTransfer.setData('text', val);
e.dataTransfer.effectAllowed = 'copy';
}
function preventDefault(e) {
e.preventDefault();
}
function dropItem(e) {
var data = e.dataTransfer.getData('text').split(',');
if (data[0] == 'car') {
var li = document.createElement('li');
li.textContent = data[1];
e.target.appendChild(li);
}
}
In the document ready function, the dataTransfer property is pushed to the collection of
properties that needs to be copied to the jQuery wrapper. The dragging function is called
when the dragging starts. It collects the data from the data-value attribute and assigns it to
the DataTransfer object. The effectAllowed property is set to copy, which changes the mouse
pointer to a pointer with a plus sign under it. If the setting were set to move, the mouse
pointer would be a pointer with a small box under it. If the effectAllowed property were set
to link, the mouse pointer would be a pointer with a shortcut symbol under it.
The dropItem function is called from the drop event. The DataTransfer object is also avail-
able on the drop event through the dataTransfer property. The data is retrieved, split into an
array, and assigned to the data variable. Next, the first element is tested to see whether it is
a car. If so, a new list item is created, and the car make, which is in data[1], is assigned to the
textContent property of the list item. Finally, the list item is appended to the drop element.
Figure 13-4 shows the finished screen after a car has been dragged and dropped to the
favorite car list.