Hex Grid Widget
A simple jQuery Hex grid Widget, implemented using SVG, for prototyping hex-grid based games.

click around the grid


About

This opensource tiny (1.5KB, < 40 lines) jQuery plugin turns any DIV into an hexagonal grid widget, for prototyping hex-grid based games in HTML. Here are the key features:

  • No magic - just plain DOM, works in all browsers, easy to manipulate
  • Does not force any styling (so you can style it any way you want, using normal CSS)
  • Fields can are clickable, and the grid has dispatches an event with row and column position for easy click handling
  • Fields have DOM attributes attached to signal row and column position, so you can easily select them using jQuery or DOM selectors.
  • Fields have jQuery meta-data attached to point to the center of the field, so you can easily put other objects on them and position relative to the grid

View project on Github

Usage

Initialise the grid by calling hexGridWidget:

$('#container').hexGridWidget(radius, columns, rows, cssClass)

Use the hex-row and hex-column DOM attributes to select an individual hex in the grid. For example:

$('#container [hex-row=2][hex-column=3]')

Capture clicks by listening to a hexclick event on the grid container DOM element.

$('#container').on('hexclick', 
 function (e) { 
  console.log('clicked [' + e.column + ',' + e.row +']' +
  ' hex with center at [' + e.center.x + ',' + e.center.y + ']');
 }
);
Alternatively, just assign a normal click handler to individual hex field, or even a group of hexfields.
$('#container .hexfield').click(function () {
  this.classList.toggle('clicked');
});
Fork me on GitHub