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

2

I have a DIV A, which moves on screen by clicking the keys on the keyboard. Is it possible to identify if this DIV A is on a DIV B using some script and trigger an event when the position of that div is recognized over 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');
        }
    };
});
    
asked by anonymous 18.06.2017 / 08:42

1 answer

3

You could use getBoundingClientRect() to get a collision box and use some math to test if the 2% with% s are colliding.

Demo: no codepen

    
18.06.2017 / 17:53