Divs collision and blast

by Chandana Thota

HTML

<!--  Image change and blast after collision --> 

    <div id="box"></div>
<div id="box1">  
</div>
<span style="margin-left:400px;color:red;font-size:40px;" id="result">false</span>

CSS

#box1{
position:absolute;
    width:100px; height:100px;          
    top:200px;
    left:200px; 
    background:url('http://ecx.images-amazon.com/images/I/31wtyWRrnIL._SL500_SS100_.jpg');
    background-repeat:no-repeat;
    
  } 
#box {
    position:absolute; 
height:100px;width:100px;
top:10px;left:10px;    background:url('http://images2.wikia.nocookie.net/__cb20101117030135/frontierville/images/e/e3/Cute_Teddy_Bear-icon.png');
    background-repeat:no-repeat;
    
}

JavaScript

//detecting key strokes

$(document).keydown(function(pk){
var pos = $('#box').position();
  if(pk.keyCode == '37'){
      $('#box').css('left',pos.left - 10 + 'px');
  }
    if(pk.keyCode == '38'){      
     $('#box').css('top',pos.top - 10 +'px');      
  }
    if(pk.keyCode == '39'){
           $('#box').css('left',pos.left + 30 + 'px');
  }
    if(pk.keyCode == '40'){
         $('#box').css('top',pos.top + 10 + 'px');
  }
    var result = collision($('#box'), $('#box1'));
if(result == true){
    $('#box').hide();
  $('#box1').css('background','url(http://tile.mapfluence.com/2.0/icons/icon_blast_black_64.png)').css('background-repeat','no-repeat');
    setTimeout(fade_out, 200);
 function fade_out() {
  $("#box1").fadeOut().empty();
}
}
  });

//detecting divs collision
    function collision($div1, $div2) {
      var x1 = $div1.offset().left;
      var y1 = $div1.offset().top;
      var h1 = $div1.outerHeight(true);
      var w1 = $div1.outerWidth(true);
      var b1 = y1 + h1;
      var r1 = x1 + w1;
      var x2 = $div2.offset().left;
      var y2 = $div2.offset().top;
      var h2 = $div2.outerHeight(true);
      var w2 = $div2.outerWidth(true);
      var b2 = y2 + h2;
      var r2 = x2 + w2;
        
      if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
      return true;
    }

//detect collision for every 2 seconds
window.setInterval(function() {
    $('#result').text(collision($('#box'), $('#box1')));
}, 200);