Drag and Drop - Exercise

Contact Us or call 1-877-932-8228
Drag and Drop - Exercise

Drag and Drop

Duration: 15 to 25 minutes.

In this exercise, you will use the HTML5 drag-and-drop API to keep track of how many times the a draggable element has been dropped into each of two elements: Drag and Drop Count In the screen shot pictured, the red (draggable) element has been dropped a total of six times: twice onto the left element and four times onto the right element.

Open html5-apis/Solutions/drag-and-drop.html in a browser to see the working code in action.

  1. Open html5-apis/Exercises/drag-and-drop.html, html5-apis/Exercises/dragdrop/script.css, and html5-apis/Exercises/dragdrop/script.css in your editor.
  2. Note that most of the code is done for you: you won't need to edit drag-and-drop.html nor script.css - script.js is the only file you will modify.
  3. Note, too, that we've left the other event-handling functions (handleDragStart, handleDrag, etc.) in the code but aren't making use of them in this example - but feel free to add extra functionality here, if you like.
  4. Add the JavaScript code necessary to display the appropriate count of drops - you will need to write the body of function handleDrop.


var dropzoneleft, drag, dropzoneright;
var dropleftcount = 0, dragcount = 0, droprightcount = 0;

function dragDrop() {
	dropzoneleft = document.getElementById("dropzoneleft");
	drag = document.getElementById("drag");
	dropzoneright = document.getElementById("dropzoneright");
---- C O D E   O M I T T E D ----

	dropzoneleft.addEventListener("drop", handleDrop, false);
---- C O D E   O M I T T E D ----

	dropzoneright.addEventListener("drop", handleDrop, false);

---- C O D E   O M I T T E D ----

function handleDrop(e) {
	var droppedOnElem = this.id;
	var countToDisplay;
	if (droppedOnElem == 'dropzoneleft') {
		dropleftcount = dropleftcount + 1;
		countToDisplay = dropleftcount;
	} else {
		droprightcount = droprightcount + 1;
		countToDisplay = droprightcount;
	this.innerHTML = "<p>Count: " + countToDisplay + "</p>";

	dragcount = dragcount + 1;
	document.getElementById("drag").innerHTML = "<p>Count: " + dragcount + "</p>";

	//document.getElementById("output").innerHTML+="<li><strong>" + droppedElem + "</strong> dropped on <strong>" + this.id + "</strong></li>";

---- C O D E   O M I T T E D ----

In function handleDrop, we find the element upon which #drag was dropped, update the appropriate counter variable, and display the appropriate counter variable on the correct landing-zone element. We increment the total count (dragcount) of all drops and display on the #drag element.