Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function only affects first div with class

I have part of a game where the cursor is supposed to "slow down" when it passes over certain divs. I'm using a function that can detect a collision with the div. This works fine when the cursor meets the first div, but it doesn't work at all on the second div.

Check out this jsFiddle for a better idea of what I'm talking about. Pass the cursor over the first white block (class='thing') on the left and it slows down. Pass the cursor over the other block (also class='thing'), and nothing happens. I need this collision function to work on all divs where class='thing'.

HTML

<div id='cursor'>
            &nbsp;
        </div>
        <div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 350px; right: 800px; z-index: -1;'>
            &nbsp;
        </div>
        <div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 200px; right: 400px; z-index: -1;'>
            &nbsp;
        </div>

JS

(function collide(){
var newInt = setInterval(function() {
function collision($cursor, $thing) {
    var x1 = $cursor.offset().left;
    var y1 = $cursor.offset().top;
    var h1 = $cursor.outerHeight(true);
    var w1 = $cursor.outerWidth(true);
    var b1 = y1 + h1;
    var r1 = x1 + w1;
    var x2 = $thing.offset().left;
    var y2 = $thing.offset().top;
    var h2 = $thing.outerHeight(true);
    var w2 = $thing.outerWidth(true);
    var b2 = y2 + h2;
    var r2 = x2 + w2;

    // change 12 to alter damping higher is slower
    var varies = 12;    

    if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2){
    } else {
    varies = 200;
    console.log(varies);
    }
$xp += (($mouseX - $xp)/varies);
    $yp += (($mouseY - $yp)/varies);
    $("#cursor").css({left:$xp +'px', top:$yp +'px'}); 

}

$(collision($('#cursor'), $('.thing')));
//$('.result').text(collision($('#cursor'), $('.thing')));

}, 20);
})();
like image 468
jack_of_all_trades Avatar asked Oct 01 '15 05:10

jack_of_all_trades


1 Answers

$thing is a collection of elements, like you want, but the problem here is that you ask specific attributes from $thing like offset().left;, which can not return more than one number, therefor it just takes the first. What you should do instead is use an .each() function to loop over all the elements in $thing.

$thing.each( function( index, element ){
    //your code for each thing here
});
like image 143
Bas van Stein Avatar answered Oct 04 '22 03:10

Bas van Stein