title: Efficient way to check adjacent tiles in a grid in javascript
body: <p>So, I want be able to detect adjacent tiles in a grid in which each tile has a <code>data-id</code> attribute starting by 1.</p>
  
  <p><a href="https://jsfiddle.net/jf3dxww0/1/" rel="nofollow">Fiddle</a></p>
  
  <p>This is the code:</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;div class="grid"&gt;&lt;/div&gt;
  </code></pre>
  
  <p><strong>JS</strong></p>
  
  <pre><code>var rows = 7;
  var cols = 9;
  var size = 50;
  
  $('.grid').css({
      width: size*rows+'px',
    height: size*cols+'px'
  });
  
  for(var i = 0; i &lt; rows*cols; i++){
      $('.grid').append('&lt;div class="tile" data-id="'+(i+1)+'" style="width: '+size+'px; height: '+size+'px"&gt;&lt;span&gt;'+(i+1)+'&lt;/span&gt;&lt;/div&gt;');
  }
  
  function checkAdjacentPossibilities(id){
      i = parseInt(id);
      var array = [];
      if(i==1){
      array.push(false, false, true, true)
      }else if (i&gt;1 &amp;&amp; i&lt;rows){
          array.push(false, true, true, true);
      }else if (i==rows){
          array.push(false, true, false, true);
      }else if (i%rows==1 &amp;&amp; i&gt;1 &amp;&amp; i&lt;(rows*cols)-rows){
          array.push(true, false, true, true);
      }else if(i==(rows*cols)-rows+1){
          array.push(true, false, true, false);
      }else if(i&gt;(rows*cols)-rows+1 &amp;&amp; i &lt; rows*cols){
          array.push(true, true, true, false);
      }else if(i==rows*cols){
          array.push(true, true, false, false);
      }else if(i%rows==0 &amp;&amp; i&gt;rows &amp;&amp; i&lt;rows*cols){
          array.push(true, true, false, true);
      }else{
          array.push(true, true, true, true);
      }
  
    $('.tile').css('background', 'transparent');
  
    for(var n = 0; n &lt; array.length; n++){
      var index = n;
      var value = array[n];
  
      if(value){
          if(index==0){
              $('.tile[data-id="'+(i-rows)+'"]').css('background', 'red');
        }else if(index==1){
          $('.tile[data-id="'+(i-1)+'"]').css('background', 'red');
        }else if(index==2){
          $('.tile[data-id="'+(i+1)+'"]').css('background', 'red');
        }else{
          $('.tile[data-id="'+(i+rows)+'"]').css('background', 'red');
        }
      }
  
  
    }
  
  }
  
  $(document).on('click', '.tile', function(){
      var $this  = $(this);
    var id = $this.attr('data-id');
    checkAdjacentPossibilities(id);
  });
  </code></pre>
  
  <p>I hardcoded all the 9 possibilities into an if/else statement:</p>
  
  <ul>
  <li>4 corners</li>
  <li>top tiles</li>
  <li>left tiles</li>
  <li>bottom tiles</li>
  <li>right tiles</li>
  <li>center blocks</li>
  </ul>
  
  <p>Is there a more efficient way of doing this? Thanks in advance</p>