Reputation: 792
Problem how can I overlay a div inside a td?
Codepen penHere
Explanation
I generate a random map inside a table, this is the function that print it :
function mapGenerate(map){
//loop the 2d array map and change the number with the appropriate img
for(var i = 0; i < map.length; i++) {
var innerArrayLength = map[i].length;
for(var j = 0; j<innerArrayLength; j++){
if(map[i][j] === 0){
map[i][j]="<div class=\"tile\"><img class=\"walkable\" src=\"https://image.ibb.co/bGanFz/floor_Resized.png\"></div>";
}else{
map[i][j]="<img class=\"nonWalkable\" src=\"https://image.ibb.co/m9s1az/volcanoresize.png\">";
}
;
}
$("#tableGame").append("<tr><td>"+ map[i].join('</td><td>') + "</td></tr>")
}
}
the map is a 2d random generated array, something like this:
map = [[1,1,1,1,0],
[1,0,0,0,0],
[1,0,1,1,1],
[1,0,0,0,1],
[1,1,1,0,1]]
and these are the Css regarding the style of the table and the image of the characters:
table {
background-color: black;
border-collapse: collapse;
border: 2px solid white;
box-shadow: 1px 1px 30px white;
}
tr {
border: 0px;
padding: 0px;
margin:0px;
}
td {
border: 0px;
padding: 0px;
margin:0px;
}
#tableGame .td {
position: relative;
}
.char {
z-index: 1000;
}
#tableGame .char {
position: absolute;
}
Task: the character image have to spawn over the div with the walkable tile, not below this.
attempts: I tried to set relative on td, but the char image just disappear, and I don't know why.
Where is the error ? Any advice will be appreciated.
Upvotes: 2
Views: 274
Reputation: 2590
Adding the Char to the .tile DIV not to the td should do the trick:
function place(coord, char){
var charImage = $("<img>").attr("src", char.image).addClass('char');
var row = $($("#tableGame tr")[coord.row]);
var cell = $($("td", row)[coord.cell]);
var tile = $($(".tile", row)[0]);
tile.prepend(charImage);
};
https://codepen.io/anon/pen/RYKZYq
Note that the Char has do be the first child of the .tile DIV. So you have to use .prepend() instead of .apend()
Upvotes: 1