0

I have two divs (rectangles) that overlap each other. How do I determine the amount of intersection/overlap between the two divs in javascript?

I realize I'll get the dimensions for each rectangle:
offset.top, offset.left, elt.offsetWidth, elt.offsetHeight

But from there I'm unsure how to determine the amount of overlap.

jaysonp
  • 1
  • 3
  • 1
    "Amount" is a tad relative. We talking pixels, inches, miles? Also, what have you tried so far? – Brad Christie Jun 09 '11 at 19:17
  • possible duplicate of [How to check if an element is overlapping other elements?](http://stackoverflow.com/questions/12066870/how-to-check-if-an-element-is-overlapping-other-elements) – Gajus Aug 19 '15 at 18:35

1 Answers1

2
var div1 = $('#div1');
var div2 = $('#div2');
var both = div1.add( div2 );

var leftMost = (div1.offset( ).left < div2.offset( ).left ? div1 : div2);
var rightMost = both.not( leftMost );
var topMost = (div1.offset( ).top < div2.offset( ).top ? div1 : div2);
var botMost = both.not( topMost );

var overlap = {   'x': (leftMost.offset( ).left + leftMost.outerWidth( )) - rightMost.offset( ).left,
                  'y': (topMost.offset( ).top + topMost.outerHeight( )) - botMost.offset( ).top };
KOGI
  • 3,959
  • 2
  • 24
  • 36