Created
July 24, 2013 16:42
-
-
Save xtrasmal/6072254 to your computer and use it in GitHub Desktop.
JS/HTML Clickable grid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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