- by gowthamk91
Introduction:
jQuery draggable collision is a plugin to detect the collision between the element while dragging within a containment. This blog explains how to detect and avoid the collision between two elements while doing drag and drop using jQuery UI and the plugin.
Install jQuery Draggable Collision Plugin:
Step 1: Click here to download the plugin package.
Step 2: Extract the .rar file, you can find some html page with the examples and the JS library files, as shown in below figure.

Step 3: Try below code to detect and avoid the collision between two elements while doing drag and drop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.8.3.min.js"></script>
<script src="ui/jquery.ui.core.js"></script>
<script src="ui/jquery.ui.widget.js"></script>
<script src="ui/jquery.ui.mouse.js"></script>
<script src="ui/jquery.ui.draggable.js"></script>
<script src="jquery-collision.min.js"></script>
<script src="jquery-ui-draggable-collision.min.js"></script>
</head>
<body>
<div id="moveHere">
<div class="draggable notHere">Drag me...</div>
<div class="draggable notHere ">...Drag me...</div>
</div>
<script>
$(".draggable").draggable({
obstacle:".notHere",
preventCollision: true,
containment: "#moveInHere",
start: function(event,ui) {
$(this).removeClass('notHere');
},
stop: function(event,ui) {
$(this).addClass('notHere');
}
});
</script>
<style>
#moveHere {
with: 500px;
height: 500px;
border: 1px solid black;
background: #eee;
}
.draggable{
width: 50px;
height: 50px;
border: 1px solid black;
background: #eee;
}
</style>
</body>
</html>
- Enable the ‘preventCollision’ property to avoid the collision.
- .notHere class is used to define the obstacle object.
- In the start event, we removed the ‘.notHere’ class so the further drag event will not consider the active object as an obstacle, once the drag stops the ‘.notHere’ class is added to make that object as an obstacle.