One way to check if two <img>
elements are touching or overlapping with each other is to utilize the $.position()
, $.height()
and $.width()
functions to retrieve the top-left position, height and width of each element, respectively.
Using these functions, you can then calculate the four coordinates, top-left, top-right, bottom-left and bottom-right, of your image element. Each coordinate should have an x-coordinate and a y-coordinate. Then you will also have to implement your overlap
algorithm to check the image elements' coordinates to see if they are touching or overlapping with each other.
You can take a look at this fiddle.
- The
coordinates
function calculates the four coordinates of an element.
- The incomplete
overlap
function checks the coordinates of the two element.
- You can slide the second image horizontally by changing the value of the
right
css property.
Like I said, the overlap
function is incomplete; it only checks if the top x-coordinates of both elements touch/overlaps. (Not gonna do the whole thing for you :-))
There may be other simpler ways to do this, but this works for a game that I built.