Search code examples
javascriptjquerycollision-detection

Detecting in jquery whether two divs pass over each other


Hi i am struggling with the following

i have knocked up a little sample to try and show what i am trying to do.

http://jsfiddle.net/4F4f8/2/

What i want to happen is when the red line passes over the blue line get the red lines data attribute comment.

i am trying to use jquery closest to detect the closest div like below.

var count = 1; 
setInterval(function(){

    leftPixels = count++;
    console.log(leftPixels);
    $('.scruber').css('left','-' + leftPixels * 10 + 'px');

    var markerData = $('.eventLine').closest('.marker').data('comment');

    $('.output').html(markerData);
    console.log(markerData);

},1000);

Would really appreciate some help with this

Thanks


Solution

  • You can do this using document.elementFromPoint(x, y); Here is an example.

    Tested on Chrome:

    http://jsfiddle.net/4F4f8/18/

    var getElementBelowMe = function($me) {
        var $below,
            elOffset = $me.offset(),      
            x        = elOffset.left + $me.width() / 2,
            y        = elOffset.top + $me.height() / 2;
    
        $me.css("visibility", "hidden");
        $below = document.elementFromPoint(x, y);
        $me.css("visibility", "");
        return $below;
    }
    
    var count = 1; 
    setInterval(function(){
    
        leftPixels = count++;
        var scruber = $('.scruber');
        scruber.css('left','-' + leftPixels * 10 + 'px');
    
        var eventLine = $('.eventLine');
    
        var markerData = getElementBelowMe(eventLine);
        if(markerData && $(markerData).hasClass("marker")) {
            var txt = "Passing " + $(markerData).data("comment");
            console.log(txt);
            $(".output").append(txt + "<br />");
        }
    
    },100);
    

    There are several things you must keep in mind though:

    • The example works by finding the center of the event line and checking what is below. This works in your current setup, but could fail if you checkPoints are narrower, and eventLine - wider.
    • elementFromPoint support is somewhat buggy or lets say different (http://www.quirksmode.org/blog/archives/2010/06/more_ie9_goodne.html#link2) in different browsers.
    • I use visibility in the example, because display: none, could actually change other elements' position and thus provide unexpected results, but you can be better with it, test..
    • Having markers coordinates in some structure and checking which is the closest as @Archer proposed in the comments could be better solution