This is a very interesting problem.
The problem, as you so rightly indicate, is in the JavaScript file.
The first problem I can see is the way you are setting div.style.gridColumnStart
in the initTile
function (also known as method). grid.style.gridColumnStart
is not a function, but a setting (also known as property), so you should just assign a value to it with =
. This is the same for the three other function calls which you have tried to make: div.style.gridColumnEnd
, div.style.gridRow
, and div.style.gridRowEnd
.
The second problem I can see is the way that you are using the variables inside of your inner function tilex
and tiley
. These variables are not visible at this point due to global, local, function, and block scoping of variables. So, you should refer to them as this.tilex
and this.tiley
.
So the four function calls you tried to make should be:
div.style.gridColumnStart = this.tilex;
div.style.gridColumnEnd = this.tilex + 1;
div.style.gridRow = this.tiley;
div.style.gridRowEnd = this.tiley + 1;
Also, you should call getElementById()
on the document
object.
function Tile(tilex, tiley) {
this.tilex = tilex;
this.tiley = tiley;
this.initTile = function initTile() {
var div = document.createElement('div');
div.id = ("tile" + this.tilex + "_" + this.tiley);
div.className = "tile";
div.innerHTML = this.tilex + "_" + this.tiley;
div.style.gridColumnStart = this.tilex;
div.style.gridColumnEnd = this.tilex + 1;
div.style.gridRow = this.tiley;
div.style.gridRowEnd = this.tiley + 1;
document.getElementById("tileGrid").appendChild(div);
}
}
let tile7_1 = new Tile(7, 1);
tile7_1.initTile();
let tile2_6 = new Tile(2, 6);
tile2_6.initTile();
let tile4_3 = new Tile(4, 3);
tile4_3.initTile();
let tile7_7 = new Tile(7, 7);
tile7_7.initTile();
body {
background-color: rgba(236, 150, 119, 0.726);
}
/*15 25*/
.grid {
display: grid;
}
#tileGrid {
background-color: rgb(20, 20, 20);
padding: 2px;
grid-template-columns: repeat(15, 20px);
grid-template-rows: repeat(25, 20px);
grid-auto-columns: 20px;
}
.tile {
background-color: rgba(100, 200, 100, 0.8);
border: 1px solid rgb(20, 20, 20);
font-size: 10px;
}
<div class="grid" id="tileGrid">
<div class="tile" id="tile1">1</div>
<div class="tile" id="tile2">2</div>
<div class="tile" id="tile3">3</div>
<div class="tile" id="tile4">4</div>
</div>
1
solved Problem with JavaScript and adding a div to a grid at a specific (row, column) position [closed]