How can I set an image as an td background? - javascript

I'm trying to set each td as a different image that I have saved as imgn.gif. (n being image number, I have 13 images, img1.gif., img2.gif... img13.gif) I have a code that generates the table now I just can't figure out how to set a background image, preferably so that the n imgn.gif changes to the next index so the next td will have the next image.
this is the code that I have for now. I assume I have to set something differently here: const cellText = document.createTextNode(2);, so it sets background-image instead?
function options ()
{
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(2);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}

just add 5 lines in you actual code:
options();
function options() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
const nbImage = 13;
let curImage = 1;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
if (curImage > nbImage) {
curImage = 1;
}
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
const cellText = document.createTextNode(2);
cell.appendChild(cellText);
row.appendChild(cell);
curImage += 1;
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
I've added:
nbImage (13 from your post)
curImage to iterate through your 13 images
After your cell creation, checking the image number:
if (curImage > nbImage) {
curImage = 1;
}
So your fourteenth TD will have the image 1
Your is already created as a DOM element so you can refer it and add a background image:
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
That will add for each TD a backgound image "img1.gif", "img2.gif"... till "img13.gif", after "img1.gif" ... and so on...

You can create a variable (nImage for exemple) starting from 1 to 13 and reset it when up to 13 so it came back to 1. Then use this variable to modify style.backgroundImage of your td :
function options ()
{
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
let nImage = 1 ;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(2);
if (nImage > 13){nImage =1 ;}
cell.style.backgroundImage = "url('yourPathTo/img"+nImage + ".gif')" ;
nImage++ ;
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}

Related

How to create a working identifier for the cells of this table?

I'm trying to give each cell of a table an identifier like in this photo
this is what I tried but it's not working:
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;// <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier;// <--------this is the problem
}
}
document.getElementById("main").appendChild(board);
}
First of all, instead of custom properties you should use data attributes and instead of the width and height attributes you should use CSS. Second, you were incrementing identifier by itself, so it wouldn't grow from 0.
const GRID_SIZE = 6;
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.dataset.identifier = identifier;
cell.innerText = identifier;
row.appendChild(cell);
identifier++;
}
}
document.getElementById("main").appendChild(board);
}
init();
main>table td {
width: 20px;
height: 20px;
}
<main id="main"></main>
Also, you don't need to store the coordinates of the cell, since you can calculate them from the identifier like this:
row = Math.floor(identifier / GRID_SIZE);
column = identifier % GRID_SIZE;
GRID_SIZE*i+j;
put it inside the cell using cell.innerHTML=GRID_SIZE*i+j;
function init(GRID_SIZE) {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0; // <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.innerHTML = GRID_SIZE * i + j;
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier; // <--------
}
}
document.getElementById("main").appendChild(board);
}
init(10)
<div id="main"></div>

Javascript : Creating a dynamic table with column title on the first row and row title in the first column

I am trying to create a table with title to be displayed on the first and second row and first column. The first row will have the same name which is working fine. But with my below script the row title (starting from 3rd row) displays in the last column than the first.
Please advise where am I going wrong with this.
var body = document.getElementsByTagName("body")[0];
var yardName = "B1";
var colsInYard = 5;
var rowsInYard = 5;
var tbl = document.createElement("table");
tbl.setAttribute("id", "our_table");
var tblHead = document.createElement("thead");
for (var r = 0; r < 1; r++) {
// creates a table row
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(yardName);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
for (var r = 0; r < 1; r++) {
var row = document.createElement("tr");
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c != 0) {
var cellText = document.createTextNode(c);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cellText = document.createTextNode(" ");
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblHead.appendChild(row);
}
tbl.appendChild(tblHead);
var tblBody = document.createElement("tbody");
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "0");
tbl.setAttribute("cellpadding", "0");
tbl.setAttribute("cellspacing", "0");
My fiddle https://jsfiddle.net/udopgxLv/1/
I believe you just need to add an IF statement to the code in the tbody section to get the data to post into the first column. I modified your jfiddle with the code below (just 2 lines added) and the values are inserted properly.
for (var r = 1; r <= rowsInYard; r++) {
var row = document.createElement("tr");
var cellText = document.createTextNode(r);
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c==1){ // <--- this was added
cell.appendChild(cellText);
} // <--- this was also added
row.appendChild(cell);
}
tblBody.appendChild(row);
}
You missed if statement in create tbody
for (var c = 0; c <= colsInYard; c++) {
var cell = document.createElement("td");
if (c=== 0)
cell.appendChild(cellText);
row.appendChild(cell);
}
https://jsfiddle.net/udopgxLv/3/

Memory game board creation, javascript

Im trying to make a memory game in javascript, but im having problems with creating the board + adding an event handler(click) to the images that are going in the table data. heres the code snippet:
var board = document.getElementById("board");
var img = document.createElement("img");
var NUM_ROWS = 6;
var NUM_COLS = 6;
for (row = 0; row < NUM_ROWS; row++) {
var tr = document.createElement("tr");
for (col = 0; col < NUM_COLS; col++) {
var td = document.createElement("td");
var img = document.createElement("img");
tr.appendChild(td);
img.src = 'images/image0.png';
tr.appendChild(img);
}
board.appendChild(tr);
}
There are many ways to do this. One way that gives you a lot of flexibility is to build up a string version of the image element that has all the features that you need and insert it into your table cell element by setting td.innerHTML as follows:
function myclick(row,col) {
// handle the click here
}
var board = document.getElementById("board");
var NUM_ROWS = 6;
var NUM_COLS = 6;
for (var row = 0; row < NUM_ROWS; row++) {
var tr = document.createElement("tr");
for (col = 0; col < NUM_COLS; col++) {
var td = document.createElement("td");
var src = "images/image0.png";
var img = '<img src="'+src+'" onclick="myclick('+row+','+col+');">';
td.innerHTML = img;
tr.appendChild(td);
}
board.appendChild(tr);
}
In this case, the img element is created with the onclick function built in and will provide the row and column of the click to your click handling function.

How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page

How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Categories