I'm trying to fill a div with different color tiles, to do this I have a HTML with a <div id="field">
, and the following javascript code:
// I want field to be globally accessible
var field;
var colors;
$(document).ready(function(){
field = [[],[],[],[],[],[],[],[],[]];
colors =["black","yellow","blue","green","grey","brown"];
fillField();
$(".tile").on('click', function(){
console.log("sfadfd");
var x = this.getAttribute("data-x");
var y = this.getAttribute("data-y");
console.log("X: "+x+", Y: "+y);
tileClicked(x,y);
});
});
var tileClicked = function(x,y){
console.log(colors[field[y][x]]);
field[y][x] = 0;
showField();
};
// Displays the field into a neat grid with pretty colors
var showField = function(){
console.log("Test");
$(".tile").remove();
for (var i = 0; i<field.length; i++){
for (var j = 0; j<10; j++){
var color = colors[field[i][j]];
$("#field").append("<div data-x="+j+" data-y="+i+" class=tile style=background-color:"+color+" ></div>");
}
console.log("Test3");
}
}
// Fills empty slots in the field
var fillField = function(){
for (var i = 0; i<field.length; i++){
for (var j = 0; j<10; j++){
var next = Math.floor(Math.random()*5+1);
if(next == field[i][j-1] ){
field[i][j] = Math.floor(Math.random()*5+1);
}
else { field[i][j] = next;}
}
}
showField();
}
The problem is that it only removes and displays the tiles once, I think it has something to do with the append() and the remove(), but I can't figure out what's wrong
Thanks!