Week 12

Task 2
 avatar
user_1373341
html
7 months ago
2.0 kB
1
Indexable
Never
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Question 2</title>
	<style type="text/css">
		.count{
			font-size: 40px;
			border-style: solid;
			border-color: black;
			border-width: 1px;
		}
	</style>
</head>
<body>
	<h3>Drag an animal and drop it on the corresponding text.</h3>

	<span class="count">
		<span id="dogSpan" ondrop="drop(event)" ondragover="dragOver(event)">dog</span> 
		<span id="dogCounterSpan">0</span>
	</span>
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	<span class="count">
		<span id="catSpan" ondrop="drop(event)" ondragover="dragOver(event)">cat</span> 
		<span id="catCounterSpan">0</span>
	</span><br/><br/>

	<img src="cat.jpeg" height="200" width="120" draggable="true" ondragstart="dragStart(event)" id="cat">
	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	<img src="dog.jpeg" height="200" width="120" draggable="true" ondragstart="dragStart(event)" id="dog">

	<script type="text/javascript">
		var dogCount = 0;
		var catCount = 0;

		function dragStart(event) {
			var dragId = event.target.id; // get the drag element id
			console.log("Drag ID: " + dragId);

			event.dataTransfer.setData("dragId",dragId); // store drag id into dataTransfer object
		}

		function drop(event) {
			var dogCounterSpan = document.getElementById("dogCounterSpan");
			var catCounterSpan = document.getElementById("catCounterSpan");

			var dropId = event.target.id; // get the drop element id
			console.log("Drop ID: " + dropId);

			var dragId = event.dataTransfer.getData("dragId"); // retrieve drag id from dataTrasfer object
			console.log("Drag ID in drop event: " + dragId);

			if (dropId == "dogSpan" && dragId == "dog") {
				dogCount++;
				dogCounterSpan.innerHTML = dogCount;
			} 

			if (dropId == "catSpan" && dragId == "cat") {
				catCount++;
				catCounterSpan.innerHTML = catCount;
			}
		}

		function dragOver(event) {
			event.preventDefault();
		}
	</script>
</body>
</html>