Would it be possible to identify if a DIV is over another DIV using some type of script?

Asked

Viewed 544 times

2

I have a DIV A, which moves on screen by clicking on the keyboard keys. It would be possible to identify if this DIV A is on one DIV B using some script and trigger an event when being recognized the position of that div on the other?

Code to Move the DIV - A on screen

$(document).ready(function() {

    var top = 0;
    var left = 0;

    function keyPressed(evt){
        evt = evt || window.event;
        var key = evt.keyCode || evt.which;
        return String.fromCharCode(key);
    }

    document.onkeypress = function(evt) {
        var str = keyPressed(evt);

        if(str == "w" || str == "W"){

            top = top -4;
            jQuery(".person").css({ top: top + '%'});
            jQuery("#person").attr('src', 'View/img/person-back' + '.png');

        }else if(str == "s" || str == "S"){

            top = top +4;
            jQuery(".person").css({ top: top + '%'});
            jQuery("#person").attr('src', 'View/img/person-front' + '.png');

        }else if(str == "d" || str == "D"){

            left = left +4;
            jQuery(".person").css({ left: left + '%'});
            jQuery("#person").attr('src', 'View/img/person-right' + '.png');

        }else if(str == "a" || str == "A"){

            left = left -4;
            jQuery(".person").css({ left: left + '%'});
            jQuery("#person").attr('src', 'View/img/person-left' + '.png');
        }
    };
});
  • You can show the code you have that moves that div?

  • I updated the question and entered the code used to move the DIV on screen.

  • Can you put your HTML too? There are several .person?

  • What is a valid overlap?: when the object "touches" another, when half is superimposed or only when the whole object is inside another?

  • The overlap could be the collision between the objects, just like to identify when a and b collide between them to fire an action.

1 answer

3


You could use getBoundingClientRect() to get a collision box and use a little math to test whether the 2 ClientRects are colliding.

Demonstration: in the codepen

  • Dear friend thanks for the proposed solution. I believe this will solve my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.