Playing with SVG
by Anthony Waslaske
HTML
<div id="gridLayout" class="gridLayout">
<div id="gridHeader">
<h2>Battle Ship:</h2>
</div>
<div id="grid" class="gridContainer">
</div>
</div>
CSS
.gridContainer {
position: relative;
margin-top: 10px;
padding: 0 0 0 0;
font-family: Arial, Helvetica, Verdana, sans-serif;
}
.cell {
width: 36px;
height: 36px;
position: relative;
float: left;
z-index: 0;
font-size: 18px;
color: #888888;
text-align: center;
line-height: 36px;
border-style: solid outset;
border-width: 1px;
border-color: black;
cursor: pointer;
}
.cell:hover {
position: relative;
background: #00CCFF;
}
.cell:hover:after {
content: attr(data-hover-text);
position: absolute;
top: 2px;
left: 2px;
right: 2px;
font-size: x-small;
font-weight: normal;
font-style: normal;
color: #444444;
text-align: left;
line-height: 1;
}
JavaScript
function starter() {
var grid_rows,
grid_cols,
grid_element;
var config = {
gridContainer: "grid",
matrixContainer: "matrix",
matrixHeader: "matrixHeader"
};
(function() { //start is never called
grid_rows = 12;
grid_cols = 12;
createGrid();
})();
function createGrid() {
grid_element = $("#" + config.gridContainer);
var cell; // Contains the 1 or 0 based upon the cell selection
var newGrid = $('<div id="grid" class="gridContainer" ></div>');
for (var i = 1; i <= grid_rows; i++) {
for (var j = 1; j <= grid_cols; j++) {
var r = (j - grid_cols / 2),
s = (grid_rows / 2 + 1 - i);
//var cellDiv = "<div class='cell' data-hover-text='"+(j - grid_cols/2)+","+(grid_rows/2 + 1 - i)+"'></div>
//<div class='dot' id= '"+(j - grid_cols/2)+","+(grid_rows/2 + 1 - i)+"'></div>"
$("<div class='cell' id='" + r + "," + s + "' data-hover-text='" + r + "," + s + "'></div>")
.appendTo(newGrid);
//.on("click", cellClick);
}
}
newGrid.height(38 * grid_rows);
newGrid.width(38 * grid_cols);
grid_element.replaceWith(newGrid);
}
}
//jQuery
$(document).ready(function() {
starter();
$('div.cell').click(function() {
//increment through ordered pair until ","
var i = 0;
while (this.id[i] !== ",") {
i++;
}
//convert text to number for x and y coordinates
//if 2nd parameter of substring blank, continues for rest of string
var xCoor = parseInt(this.id.substring(0, i), 10);
var yCoor = parseInt(this.id.substring(i + 1, ), 10);
//create SVG
var point = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
//set attributes
point.setAttribute('cx', 100);
point.setAttribute('cy', 75);
point.setAttribute('r', 8);
point.setAttribute('fill', 'red');
//Add to parent node
document.getElementById('grid').appendChild(point, function() {
var sel =...