1

Say I have two divs absolutely positioned, is it possible to calculate where these two divs overlap and then draw another div to place on top of the overlapping area.

I have been searching around the web and most things I have come to is only concerned with overlap detection, like this fiddle

I don't understand how to get the following positions for the overlap area:

offsetTop
offsetLeft
width
height

Any help would be appreciated in pointing me where I would start with this.

I have this fiddle for what I have been playing with - you will see that I am trying to create a div to sit on the overlapping part and colour it a mixture of the two colours

4
  • In essence this seems to be a duplicate of how-to-find-rectangle-intersection-on-a-coordinate-plane
    – zsawyer
    Jun 12, 2013 at 13:49
  • @zsawyer That doesn't really tell me how to get the coordinates with javascript though and I'm not sure how you would apply the mathematical formula of the best answer
    – user1987162
    Jun 12, 2013 at 13:53
  • does this means anything to you? api.jquery.com/category/css
    – steo
    Jun 12, 2013 at 13:56
  • @steo, I know how to use jQuery, just not how to calculate the intersection points
    – user1987162
    Jun 12, 2013 at 13:57

1 Answer 1

5

I haven't error checked it yet, but I believe you wanting something like: http://jsfiddle.net/GApu5/4/

with the calculations as follows:

var l1=div1.offset().left-8;
var t1=div1.offset().top-8;
var w1=div1.width();
var h1=div1.height();

var l2=div2.offset().left-8;
var t2=div2.offset().top-8;
var w2=div2.width();
var h2=div2.height();    

var top = Math.max(t1,t2);
var left = (l2>l1 && l2<(l1+w1)) ? l2 : (l1>l2 && l1<(l2+w2)) ? l1 : 0;
var width = Math.max(Math.min(l1+w1,l2+w2) - Math.max(l1,l2),0);
var height = Math.max(Math.min(t1+h1,t2+h2) - Math.max(t1,t2),0);
overlay.css({'top': top, 'left': left, 'width': width, 'height': height});

and to show works all sides: http://jsfiddle.net/GApu5/5/

3
  • what are the -8 for? I copied his code into my fiddle and I had to change the top to -10
    – user1987162
    Jun 12, 2013 at 14:15
  • ah it was being pushed out by the margin and on the wrapper and body. Thanks this is perfect
    – user1987162
    Jun 12, 2013 at 14:17
  • yeah, I didn't check, but margins, padding, borders etc will affect it slightly
    – C..
    Jun 12, 2013 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.