Detect collision between two elements (jQuery)

by Marventus

HTML

<div class='a a1'></div>
<div class='a a2'></div>

CSS

div.a {
    width: 50px;
    height:50px;
    position:absolute;
}
div.a1 {
    background-color:blue;
    left:0;
    top:0;
}
div.a2 {
    background-color:red;
    left:0;
    top:100px;
}

JavaScript

/* Random element animation credit: `http://stackoverflow.com/questions/10385950/how-to-get-a-div-to-randomly-move-around-a-page-using-jquery-or-css#answer-10386178`
 * Collision detection by Marventus
*/

$(document).ready(function () {
    $(".a").each(function() {//
        animateDiv($(this));
        window.stopAnimation = false;
    });
    trackCollisions(".a", 100);
});

function trackCollisions(sel, time) {
    var timer = setInterval(function() {
        sel = $(sel);
        var collided = false,
            condX = $(sel[0]).offset().left < $(sel[1]).offset().left ? $(sel[0]).offset().left + $(sel[0]).width() - $(sel[1]).offset().left >= 0 : $(sel[1]).offset().left + $(sel[1]).width() - $(sel[0]).offset().left >= 0,
            condY = $(sel[0]).offset().top < $(sel[1]).offset().top ? $(sel[0]).offset().top + $(sel[0]).height() - $(sel[1]).offset().top >= 0 : $(sel[1]).offset().top + $(sel[1]).height() - $(sel[0]).offset().top >= 0;
        if( condX && condY ) {
            alert("Collision occurred!");
            //window.stopAnimation = true; /* Uncomment to stop animation on collision */
        }
    }, time);
}

function makeNewPosition() {
    var h = $(window).height() - 50,
        w = $(window).width() - 50,
        nh = Math.floor(Math.random() * h),
        nw = Math.floor(Math.random() * w);
    return [nh, nw];
}

function animateDiv(elem) {
    if( !window.stopAnimation ) {
        var newq = makeNewPosition(),
            oldq = elem.offset(),
            speed = calcSpeed([oldq.top, oldq.left], newq);
        elem.animate({
            top: newq[0],
            left: newq[1]
        }, speed, function () {
            animateDiv($(this));
        });
    }
}

function calcSpeed(prev, next) {
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    var greatest = x > y ? x : y;
    var speedModifier = 0.2;
    var speed = Math.ceil(greatest / speedModifier);
    return speed;
}