TAGS :Viewed: 14 - Published at: a few seconds ago

[ JQuery: any browsing divs plugin ]

Imagine i have a grid of 5x5 divs and the first one is selected with class="selected"

there is any plugin ready so i can use my keyboard arrows to navigate left/right up down in that grid?

Answer 1


I haven't seen any plugins that provide this functionality, but it is a relatively simple and fun problem so I gave it a shot.

For the HTML, structure your grid like this:

<div class="container">
  <div class="boxrow">
    <div class="box selected"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
  <div class="boxrow">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
  <div class="boxrow">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

For the styling, here is something simple to get you started:

.box {
  height: 5px;
  width:5px;
  border: 1px solid #c0c0c0;
  margin: 1px;
  float: left;
}

.selected {
  background-color: blue;
}

.boxrow {
  clear: both;
}​

And finally, here is the Javascript. You can turn this into a plugin if you want to expand the functionality.

$(document).keydown(function(event) {

    var selected = $('.selected');
    var row = selected.parent('.boxrow');
    var index = row.children('.box').index(selected);

    switch (event.keyCode) {
      case 37: // left
        if (selected.prev('.box').length != 0)
          selected.removeClass('selected').prev('.box').addClass('selected');
        break;
      case 38: // up
        var prevRow = row.prev('.boxrow');
        if (prevRow.length != 0) {
          selected.removeClass('selected');
          prevRow.children('.box').eq(index).addClass('selected');
        }
        break;
      case 39: // right
        if (selected.next('.box').length != 0) 
          selected.removeClass('selected').next('.box').addClass('selected');
        break;
      case 40: // down
        var nextRow = row.next('.boxrow');
        if (nextRow.length != 0) {
          selected.removeClass('selected');
          nextRow.children('.box').eq(index).addClass('selected');
        }
        break;
    }

});​

Have fun and hope you find this useful.

Here is a jsfiddle demo.