Skip to content

Instantly share code, notes, and snippets.

@xtrasmal
Created July 24, 2013 16:42
Show Gist options
  • Save xtrasmal/6072254 to your computer and use it in GitHub Desktop.
Save xtrasmal/6072254 to your computer and use it in GitHub Desktop.
JS/HTML Clickable grid
.grid { margin:1em auto; border-collapse:collapse }
.grid td {
cursor:pointer;
width:30px; height:30px;
border:1px solid #ccc;
text-align:center;
font-family:sans-serif; font-size:13px
}
.grid td.clicked {
background-color:yellow;
font-weight:bold; color:red;
}
var lastClicked;
var grid = clickableGrid(10,10,function(el,row,col,i){
console.log("You clicked on element:",el);
console.log("You clicked on row:",row);
console.log("You clicked on col:",col);
console.log("You clicked on item #:",i);
el.className='clicked';
if (lastClicked) lastClicked.className='';
lastClicked = el;
});
document.body.appendChild(grid);
function clickableGrid( rows, cols, callback ){
var i=0;
var grid = document.createElement('table');
grid.className = 'grid';
for (var r=0;r<rows;++r){
var tr = grid.appendChild(document.createElement('tr'));
for (var c=0;c<cols;++c){
var cell = tr.appendChild(document.createElement('td'));
cell.innerHTML = ++i;
cell.addEventListener('click',(function(el,r,c,i){
return function(){
callback(el,r,c,i);
}
})(cell,r,c,i),false);
}
}
return grid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment