-4

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!

Isha Dijcks
  • 74
  • 11

1 Answers1

2

Use event delegation beacuse you remove the element(.tile) and add dynamically

$("#field").on('click', '.tile' ,function(){

});
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49