Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when an element over another element in JavaScript?

I wrote most of the code... And when the element is "fully" over the other element it works. The problem is that I don't just want it to be true when the element is "fully" over the element, I also want it to be true when the element is partly over the other element.

Here is my code:

    element = this.element.getStyles('left', 'top', 'width', 'height');
    elementLeftX = element.left.toInt();
    elementLeftY = element.top.toInt();
    elementRightX = (element.width.toInt() + element.left.toInt());
    elementRightY = (element.top.toInt() + element.height.toInt());

    el = this.positions ? this.positions[i] : this.getDroppableCoordinates(el); // Element drop area
    elLeftX = el.left.toInt();
    elLeftY = el.top.toInt();
    elRightX = (el.width.toInt() + el.left.toInt());
    elRightY = (el.height.toInt() + el.top.toInt());

   if (((elLeftY <= elementLeftY) && (elementLeftY <= elRightY)) && ((elLeftY <= elementRightY) && (elementRightY <= elRightY))) {
        if (((elLeftX <= elementLeftX) && (elementLeftX <= elRightX)) && ((elLeftX <= elementRightX) && (elementRightX <= elRightX))) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }

I am very confused and I have been playing around for a while and I just can't get it to work.

like image 660
jnbdz Avatar asked Mar 07 '12 18:03

jnbdz


People also ask

How do you check if an element contains another element?

contains() method checks if an element is inside another, and returns a boolean: true if it is, and false if it's not. Call it on the parent element, and pass the element you want to check for in as an argument. // returns true main. contains(list); // returns false main.

How do you check if an element is a child of another element Javascript?

The Node. contains() method is used to check if a given node is the descendant of another node at any level. The descendant may be directly the child's parent or further up the chain.


1 Answers

Standard video game method:

doElsCollide = function(el1, el2) {
    el1.offsetBottom = el1.offsetTop + el1.offsetHeight;
    el1.offsetRight = el1.offsetLeft + el1.offsetWidth;
    el2.offsetBottom = el2.offsetTop + el2.offsetHeight;
    el2.offsetRight = el2.offsetLeft + el2.offsetWidth;

    return !((el1.offsetBottom < el2.offsetTop) ||
             (el1.offsetTop > el2.offsetBottom) ||
             (el1.offsetRight < el2.offsetLeft) ||
             (el1.offsetLeft > el2.offsetRight))
};

See demo

like image 171
mVChr Avatar answered Sep 17 '22 11:09

mVChr