View Full Version : How to get elements under any element?

04-29-2007, 05:21 PM
Hello all,

This may sound stupid but is it possible to get the element under any element? What I mean is ... if I have two(or more) divs, and one of them is dynamically moving around a page is it possible to get the divs that the moving division moves over?

Here's what I mean in step-by-step form:

Div A starts moving,
Div A moves over Div B and it is logged/alerted,
Div A moves over Div C; it's logged/alerted, and so on and so forth ....

How can I achieve this?

I'd be greatly appreciated if anyone could shed some light on me.

Thank you.

04-29-2007, 09:34 PM
Yes it is possible, just quite hard

you would have to write a function that was called every time the div moved.


divMoving = "divMovingID"
divArray = ["div1ID","div2ID","etc"]

function isTouching(){
var divsTouching = false
for all divs in array
if( left edge of movingDiv < right edge of static div && top edge of movingDiv < bottom egde of static div)
{divsTouching = true}

repeat for 3 other coners

if(divsTouching == true)
{do something}


05-01-2007, 06:40 AM
Sorry for the late reply.

Can't it be done without the divs/forms/any element being pre-defined? I've hooked up a function to check if the moving div is inside any element here it is:

HTMLElement.prototype.getBoundingBox = function(){
var n = this;
return {top: n.offsetTop, left: n.offsetLeft, width: n.offsetWidth, height: n.offsetHeight, bottom: n.offsetTop + n.offsetHeight, right: n.offsetLeft + n.offsetWidth};

HTMLElement.prototype.isInside = function(el){
var st = document.getElementById(el).getBoundingBox();
var ts = this.getBoundingBox();
if(ts.right > st.left && ts.left < st.right && ts.bottom > st.top && ts.top < st.bottom){
return true;
} else {
return false;

05-01-2007, 05:37 PM
Well I thinks thats close, but you only check if the div is entirely within the other. They asked for touching, which requires only 1px to touch. So a small mod is needed to check if it is touching

Nice code otherwise.


05-01-2007, 05:46 PM
Nice code otherwise.


Can this be done instead of defining the division one-by-one:

loop over all the divisions in the body and check if the moving division is
inside any of those

Not sure if it'd work but I think it will, what about you?