HTML and CSS Reference
In-Depth Information
Dragging and Dropping Files
Now that you know how to drag HTML elements and drop them onto a target element, let's see how files
can be dragged and dropped onto a web page. In the case of file drag-and-drop, you don't have to worry
about marking any HTML elements as draggable because files are external entities and you drag them
from outside the browser. You need to take care of dropping of the files.
A page may contain many HTML elements capable of acting as a drop target. However, if you want to
access the files dropped from Windows Explorer or the Desktop, you have to “listen” to known elements
designated for that purpose. To understand how to do this, let's develop a web form as shown in Figure 9-9.
Figure 9-9. Dragging and dropping files on a web form
The web form consists of a <div> element whose background image is set to the image of a basket. You
can drag files from Windows Explorer or the Desktop and drop them onto this <div> element. The <div>
handles the drop event and displays an alert box that indicates how many files were dropped. The code in
Listing 9-16 shows how the required drag-and-drop events are handled.
Listing 9-16. Handling Dropped Files
$(document).ready(function () {
var container;
container = document.getElementById("container");
container.addEventListener("dragenter", OnDragEnter, false);
container.addEventListener("dragover", OnDragOver, false);
container.addEventListener("dragleave", OnDragLeave, false);
container.addEventListener("drop", OnDrop, false);
function OnDragEnter(e) {
Search WWH ::

Custom Search