HTML and CSS Reference
In-Depth Information
droptarget.ondragover = dragOverHandler;
droptarget.ondragleave = dragLeaveHandler;
droptarget.ondrop = dropHandler;
// event handling functions for each of the drag and drop
function dragStartHandler(e) { console.log("dragstart"); }
function dragHandler(e) { console.log("drag"); }
function dragEndHandler(e) { console.log("dragend"); }
function dragEnterHandler(e) { console.log("dragenter"); }
function dragOverHandler(e) { console.log("dragover"); }
function dragLeaveHandler(e) { console.log("dragleave"); }
function dropHandler(e) { console.log("drop"); }
window.onload = init;
This script will add event handler functions for each of the drag-and-drop events and
log a message to the console when the event occurred. If you open this in a web browser
and drag the text "Draggable" to "Drop Target," you should see some event messages
appear in your JavaScript console.
Depending on the browser you used, you may not see very much. For instance,
Google Chrome shows only"dragstart" and "dragend" and appears to ignore all the other
events! What's going on here? Well, Chrome expects something called a dataTrans-
fer object to be set, which is essentially a data payload that gets (potentially) delivered
to the drop target in a drag-and-drop operation. At its simplest, a drag-and-drop opera-
tion involves the following:
• Setting the draggable attribute to true (if it isn't already)
• Setting an event listener function to handle the dragstart event
• Setting the payload of the dataTransfer object in the dragstart event
handler function
OK, so we need to add a line of code to the dragStartHandler() function to
make this script compatible with browsers such as Google Chrome. Amend the code for
the dragStartHandler() function in script.js to look like this:
function dragStartHandler(e) {
Search WWH ::

Custom Search