Code_Snippet

Thursday Tech Tip – JQuery Conditional Draggable & Droppable

I was asked for help earlier this week in updating a site with draggable and droppable UI elements with conditional behavior attached to them. More or less, I was tasked with doing the following.

  • Ability for a user to drag elements around the page to any location.
  • Conditionally change the color of the background of the main element based on the number of elements dragged into it.

I used JQuery/JavaScript to achieve this. JQuery has built in functions for making elements draggable and droppable with additional function level options for each.I thought this was a pretty cool UI tool so I am sharing a basic example of the solution here. The example changes the background of the droppable element depending on whether there are an odd or even number of other elements dropped within it. There are probably more advanced uses of this functionality you can come up with. You can preview it here or copy and paste the code below into your own local file.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
  	<script type="text/javascript" src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
	<style>
		body {
			background-color: white;
			margin: auto;
			width: 960px;
		}
		#box {
			width: 100%;
			height: 400px;
			background-color: grey;
			clear: both;
		}
		.red {
			height: 100px;
			width: 100px;
			background-color: red;
			float: left;
			margin: 5px 5px 5px 5px;
		}
	</style>
	<script>
	$(function () {
		var count = 0;

		$(".red").draggable();

	    $("#box").droppable({
                accept: ".red",
                drop: function (event, ui) {
                		count++;
                		function isOdd(count) { return count % 2;}
						if (isOdd(count) == true) {
							$(this).css("background-color", "green");
						} else {
							$(this).css("background-color", "grey");
						}
                },
                out: function (event, ui) {
                		count--;
                		function isOdd(count) { return count % 2;}
                		if (isOdd(count) == false) {
                        	$(this).css("background-color", "grey")
						} else {
							$(this).css("background-color", "green");
						}
                }
        });
	});
	</script>
	<title>Draggable and Droppable Elements</title>
</head>
<body>
<p>Draggable and Droppable Elements</p>
<div class="red">Drag Me</div>
<div class="red">Drag Me</div>
<div class="red">Drag Me</div>
<div class="red">Drag Me</div>
<div class="red">Drag Me</div>
<div class="red">Drag Me</div>
<div id="box">Drop Here</div>
</body>
</html>

Leave a Reply