0

Scenario: I have a parent <div> element that loads absolutely-positioned child <p> elements.
All these <p> elements are loaded dynamically from the database, so the parent div's number of child elements cannot be predicted - neither can their position or width (it's a different number everytime).

I'm using code from this page to detect when 2 <p> child elements overlap, however, what I'm trying to achieve is to detect overlapping (or collision) between multiple elements (I need to be watching many elements and detect each collision).

This is the code I'm using to detect between 2 elements:

function collidesWith(element1, element2) {
    var Element1 = {};
    var Element2 = {};

    Element1.top = $(element1).offset().top;
    Element1.left = $(element1).offset().left;
    Element1.right = Number($(element1).offset().left) + Number($(element1).width());
    Element1.bottom = Number($(element1).offset().top) + Number($(element1).height());

    Element2.top = $(element2).offset().top;
    Element2.left = $(element2).offset().left;
    Element2.right = Number($(element2).offset().left) + Number($(element2).width());
    Element2.bottom = Number($(element2).offset().top) + Number($(element2).height());

    if (Element1.right > Element2.left && Element1.left < Element2.right && Element1.top < Element2.bottom && Element1.bottom > Element2.top) {
        alert('Elements collide');
    }
}

How do I modify this to make it compatible with my scenario?

Mafia
  • 792
  • 2
  • 19
  • 39

1 Answers1

0

Here below is the edited code snipped according to your scenario. Be sure to read and understand before use cause I have made a lot of change here

function collidesWith() {
  var element = $('#parent p');

  element.each(function(index, val) {
    if ($(this).prev().length) {
      var Element1 = $(this).prev();
      var Element2 = $(this);
      Element1Top = $(this).prev().offset().top;
      Element1Left = $(this).prev().offset().left;
      Element1Right = Number(Element1Left) + Number($(this).prev().outerWidth());
      Element1Bottom = Number(Element1Top) + Number($(this).prev().outerHeight());

      Element2Top = $(this).offset().top;
      Element2Left = $(this).offset().left;
      Element2Right = Number(Element2Left) + Number($(this).outerWidth());
      Element2Bottom = Number(Element2Top) + Number($(this).outerHeight());

      if (Element1Right > Element2Left) {
        $(this).css('left', Element1Right);
      }

    }
  });
}

collidesWith();
body{
 margin: 0;
}
#parent {
  position: relative;
}

p {
  background-color: #333333;
  color: #ffffff;
  margin: 0;
  padding: 15px;
  position: absolute;
  box-sizing: border-box;
}

p:nth-child(2n) {
  background-color: #4a4a4a;
}
<div id="parent">
  <p>1st Element</p>
  <p>2nd Element</p>
  <p>3rd Element</p>
  <p>4th Element</p>
  <p>5th Element</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Foysal Remon
  • 301
  • 2
  • 9