Home >Web Front-end >JS Tutorial >How to Detect Collisions Between Two Divs Using JavaScript and jQuery?
How to Detect Collisions Between Two DIVs
When working with dynamic elements on a web page, it's essential to be able to detect collisions between them. In this instance, we're dealing with two simple colored divs moving perpendicular to each other.
The Solution:
To determine if the divs collide, we'll leverage JavaScript and the jQuery library. Here's a breakdown of the solution:
Example Code:
var overlaps = (function () { function getPositions(elem) { var pos, width, height; pos = $(elem).position(); width = $(elem).width(); height = $(elem).height(); return [[pos.left, pos.left + width], [pos.top, pos.top + height]]; } function comparePositions(p1, p2) { var r1, r2; r1 = p1[0] < p2[0] ? p1 : p2; r2 = p1[0] < p2[0] ? p2 : p1; return r1[1] > r2[0] || r1[0] === r2[0]; } return function (a, b) { var pos1 = getPositions(a), pos2 = getPositions(b); return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]); }; })(); $(function () { var area = $("#area")[0], box = $("#box0")[0], html; html = $(area) .children() .not(box) .map(function (i) { return '<p>Red box + Box ' + (i + 1) + ' = ' + overlaps(box, this) + '</p>'; }) .get() .join(''); $('body').append(html); });
This solution is efficient and accurate for detecting collisions between perpendicularly moving divs. It provides a useful tool for various interactive web applications, such as games and simulations.
The above is the detailed content of How to Detect Collisions Between Two Divs Using JavaScript and jQuery?. For more information, please follow other related articles on the PHP Chinese website!