How to detect if two divs are touching | jQuery

Let us imagine that we have a draggable (which allow elements to be moved using the mouse) div, and we want to check if the draggable element touches another element as it shown below:

collision jquery

HTML: 


CSS:


jQuery | JavaScript:

Collision function:

To be able to know when a div reaches another we need to calculate the current position in pixels of each div and compare it with the other.

For example, imagine we have two divs located on different positions, In order to be able to know the real amount of pixels that the components have on the screen, we need to get their height and width.

To detect whether the two divs collide, we need to calculate the onscreen position of each one.
In order to make the calculation, we need to know the top value+ height and the left + width of each one:

topPlusHieght = Height + Top
leftPlusWidth = Width + Left

Now the function runs it returns true when:

  • Div1:topPlusHieght is equal to the Div2:Top
  • Div1:topPlusHieght is equal to Div2:Left
  • Div2:topPlusHieght is equal to the Div1:Top
  • Div2:topPlusHieght is equal to Div1:Left

Update the draggable position:

By default the draggabale position doesn't update, we need to keep track of the its position when the user drag it so we can compare it with the other div, to do that we need to add: refreshPositions: true

Check the collision every certain amount of time:

In our case we don't know when the collision is going to happen so we need to run the collision function every time to check, I used setInterval() function for this purpose.

Post a Comment

1 Comments