Verify the overlay for numerous divs problem

Checking for overlaying divs using these functions:

function checkCollision($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;
}

$("#flex[data-item-id]").each(function() {    
  var id_item = $(this).data('item-id');
  var status = checkCollision($('#c + id_item), $("#r" + id_item));

  if (status) {
    $('.here').css('background-color', 'red');
  }
});

The if(status) statement is not working as expected even though the console shows "ok true" and "false" where expected.

Answer №1

As mentioned by @Rory McCrossan, it appears that there is a missing ' in your selector.

Consider using the following code:

function checkCollision($element1, $element2) {
  var x1 = $element1.offset().left;
  var y1 = $element1.offset().top;
  var h1 = $element1.outerHeight(true);
  var w1 = $element1.outerWidth(true);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $element2.offset().left;
  var y2 = $element2.offset().top;
  var h2 = $element2.outerHeight(true);
  var w2 = $element2.outerWidth(true);
  var b2 = y2 + h2;
  var r2 = x2 + w2;

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) 
    return false;

  return true;
}

$.each("#flex[data-item-id]", function() {    
  var itemId = $(this).data('item-id');
  var collisionStatus = checkCollision($('#c' + itemId), $("#r" + itemId));

  if (collisionStatus) {
    $('.here').css('background-color', 'red');
  }
});

UPDATE: I've adjusted the jQuery each function based on the jQuery each documentation. To ensure functionality, you'll need to incorporate this with your HTML code.

Answer №2

In the updated version of your collision function, it now includes checks for both vertical overlap of tops and bottoms as well as horizontal overlaps to ensure accurate detection of collisions.

function checkCollision($item1, $item2) {
  var left1 = $item1.offset().left,
    top1 = $item1.offset().top,
    bottom1 = $item1.outerHeight(true) + top1,
    right1 = $item1.outerWidth(true) + left1;

  var left2 = $item2.offset().left,
    top2 = $item2.offset().top,
    bottom2 = $item2.outerHeight(true) + top2,
    right2 = $item2.outerWidth(true) + left2;

  var isVerticalOverlap = false,
    isHorizontalOverlap = false,
    hasCollided = false;

  if (bottom1 > top2 && bottom1 < bottom2) {
    isVerticalOverlap = true;
  }
  if (bottom2 > top1 && bottom2 < bottom1) {
    isVerticalOverlap = true;
  }
  // check for vertical overlap

  if (right1 > left2 && right1 < right2) {
    isHorizontalOverlap = true;
  }
  if (right2 > left1 && right2 < right1) {
    isHorizontalOverlap = true;
  }
  // check for horizontal overlap

  if (isHorizontalOverlap && isVerticalOverlap) {
    hasCollided = true;
  }

  return hasCollided;
}
/*
$.each( "#flex[data-item-id]" , function() {    
  var id_item = $(this).data('item-id');
  var status = checkCollision($('#c' + id_item), $("#r" + id_item));

  if (status) {
    $('.here').css('background-color', 'red');
  }
}); */

$("#monitor").text(checkCollision($('#alpha'), $('#beta')));
// display the result
#alpha {
  position: absolute;
  left: 3em;
  top: 2em;
  width: 4em;
  height: 4em;
  background: #489;
}

#beta {
  position: absolute;
  left: 4em;
  top: 4em;
  width: 4em;
  height: 4em;
  background: #498;
}

#monitor {
  position: fixed;
  bottom: 1em;
  left: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="alpha"></div>
<div id="beta"></div>

<div id="monitor"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unleashing the power of jQuery, utilizing .getJSON and escaping

When I use .getJSON, the response I get is a JSON string with many \" characters. However, the callback function does not fire when the page is launched in Chrome. I have read that this happens because the JSON string is not validated as JSON (even th ...

Utilize jQuery for transferring a JavaScript array to PHP backend

Trying to pass a Javascript array to PHP using AJAX and jQuery. The simple page contains selectable numbers via jQuery UI (see below). When a group of numbers is selected, they are added to an array called "shift" using array.push. The main question is: W ...

Run the scripts that are returned from AJAX requests

Here's a helpful tip from Lucian Depold: "Instead of sending JavaScript code from PHP to JS, simply send a JSON object or array and execute each entry using the eval() function." Inside index.php, there is code that runs when the document is ready: ...

Issues with Hovering over Button Contained in Slider

I can't seem to figure this out. It should be a simple fix. I have 5 slider images with black buttons that link to different galleries. I want the button background color to change on hover, but it's only working on one of the sliders. It seems ...

TypeScript: does not match type error

I am new to using TypeScript with Angular 2. I am currently utilizing version 1 of Angular 2 CLI. During compilation, I encountered an error stating that "is not assignable to type Assignment[]". I have reviewed the data types and everything seems correct ...

Creating CSS boxes in a dual column layout with a step-by-step approach

Currently, I am in the process of developing a user interface for a menu that looks something like this: https://i.sstatic.net/GuzRm.png I am exploring different implementation methods for this design. In this project, I am utilizing Bootstrap framework. ...

HTML steps for smooth scrolling to the top and bottom of a list

My HTML contains a vertical list with top and bottom arrows positioned nearby. I am looking to implement a function where clicking on the top arrow will move the list up gradually, and clicking on the bottom arrow will move the list down step by step. Belo ...

Dual scrollbars and a collapsing toolbar

Currently immersed in the development of a photo gallery using AngularJS and Angular Material (expand to fullscreen to observe the issue). var app = angular.module('app', ['ngMaterial']); app.controller('TitleController', f ...

Saving data in a CSV file on your local device using HTML5

Is it possible to utilize HTML5 for saving or writing data to a local file on the user's file system? I am curious about this functionality, especially since HTML5 now offers the capability to export data from the client and save it as a CSV file. If ...

a variance in the line breaks within a horizontal Form Layout

I need to design a form with multiple labels and form elements such as text areas and radio buttons. However, when using the Bootstrap horizontal form method, there is a one-line difference between the label and text area in my code: <!DOCTYPE HTML> ...

Enhanced tagging functionality in Knockout v3 with Chosen Multiselect

Recently, I have been expanding the functionality of a selected library by implementing an on-the-fly tagging feature using knockout observables to store the selected values. However, I have encountered some issues along the way. I am hopeful that someone ...

Sending HTML content to viewChild in Angular 5

I'm struggling to figure out how to pass HTML to a ViewChild in order for it to be added to its own component's HTML. I've been searching for a solution with no luck so far. As a newcomer to Angular, many of the explanations I find online ar ...

An image appears fractured when placed within a table cell, yet displays perfectly when positioned outside of the table

I am currently facing an issue with loading image files in table cells using jQuery. Here is the code snippet from my View: <table id="personDataTable" border="1"> <tr style="font-size:large; height:auto"> <th width="10 ...

Retrieve the value of an li element and send it to an AJAX request

I am experiencing an issue with my treeview list where I am trying to send the id of the selected li element via ajax, but for some reason, the code is not functioning as expected. You can view the old code here: http://jsfiddle.net/esS4k/379/ Check out ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

when a choice is made

UPDATE: Oops, I forgot to include "http://" in the links. That's not what's causing my issue though. Let me correct the question... I have a few options, like so: <select class="mySelect"> <option value="http://www.url1.com">Url ...

Why does jQuery fail to function when deployed, yet it works perfectly fine in the local Nuxt.js

I am currently utilizing jQuery to showcase a popup within my Nuxt.js application, which is functioning smoothly in both localhost and the development environment. I made necessary configurations in my nuxt.config.js file. script: [ { src: "~p ...

Dropdown menu is misaligned on the screen

I am currently working on enhancing my navigation bar with a dropdown menu using Bootstrap. However, I have encountered an issue where one of the items in the menu is not displayed properly. If you would like to see the full HTML and CSS code, you can vie ...

Absence of special Polish characters when loading content via ajax using magnific popup

I'm having trouble displaying Polish characters, such as: Wype ł nij poni ż sze pola However, instead of that, I see: Wype Å nij poni ż sze pola In my main page, I've set UTF-8 and Polish encoding: <%@ page contentType="text/ht ...

Typescript encounters transpilation issues when the spread operator is omitted for undefined values {...undefined}

I am currently working on a TypeScript project where I have encountered a peculiar issue. Within some of my TypeScript files, I am including a plain JavaScript/Node file named config.js. The content of config.js is as follows: 'use strict'; modu ...