Home > Web Front-end > JS Tutorial > How to Detect Collisions Between Elements in jQuery/JavaScript?

How to Detect Collisions Between Elements in jQuery/JavaScript?

Barbara Streisand
Release: 2024-11-19 09:12:02
Original
1034 people have browsed it

How to Detect Collisions Between Elements in jQuery/JavaScript?

jQuery/JavaScript Collision Detection

Identifying Overlapping Elements

Knowing when two elements have overlapped is essential for various interactive web applications. Imagine a simple game where two colored boxes move perpendicularly on a grid. To determine whether the red box has collided with any of the other boxes, you can employ the following jQuery/JavaScript solution:

Function Breakdown

getPositions: Retrieves the position and dimensions of an element.

comparePositions: Compares the ranges of two given positions and returns true if they overlap or touch.

overlaps: The main function checks for overlap between two elements. It uses getPositions and comparePositions to determine if any of their axes overlap.

Implementation

  1. Define the overlaps function as a closure.
  2. Get the positions of the two elements being checked.
  3. Compare the horizontal and vertical ranges of both elements using comparePositions.
  4. Return true if any of the ranges overlap.

Example

Consider the HTML structure:

<div>
Copy after login

And the corresponding JavaScript:

var overlaps = (function () {
  // ... same as before ...
})();

$(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);
});
Copy after login

This script appends messages to the page indicating whether the red box overlaps with any of the other boxes.

The above is the detailed content of How to Detect Collisions Between Elements in jQuery/JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template