Detect If An Element Is Dragged Over A Drop Element - collision.js

File Size: 3.07 KB
Views Total: 2167
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Detect If An Element Is Dragged Over A Drop Element - collision.js

collision.js is a mobile-compatible jQuery plugin for jQuery UI's draggable widget that detects when a draggable object is moved over another object via mouse drag or touch move event.

How to use it:

1. Load the necessary jQuery and jQuery UI in the document.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/cdn/jquery-ui.min.js"></script>

2. Load the jQuery UI Touch Punch extension for the support of touch events.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>

3. Create drag and drop elements.

<div id="div1">Drop Here</div>
<div id="div2">Drag Me</div>

4. The main function to detect if DIV 2 is draggaed over DIV 1.

function collision($div1, $div2) {
  var x1 = $div1.offset().left;
  var y1 = $div1.offset().top;
  var h1 = $div1.outerHeight(true);
  var w1 = $div1.outerWidth(true);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $div2.offset().left;
  var y2 = $div2.offset().top;
  var h2 = $div2.outerHeight(true);
  var w2 = $div2.outerWidth(true);
  var b2 = y2 + h2;
  var r2 = x2 + w2;
  if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
  return true;
}

5. Enable the draggable functionality on DIV 2.

$('#div2').draggable({
  refreshPositions: true
});

6. Do something when DIV 2 is draggaed over DIV 1.

if (collision($('#div1'),$('#div2')))
  // do something
else 
  // do something

This awesome jQuery plugin is developed by wadiemendja. For more Advanced Usages, please check the demo page or visit the official website.