This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
Im trying to make a game board that has click functions on every cell, but every time i click on a cell the only one that gets affected is the very last cell.
i would appreciate some help on this.
heres my code for the table:
var board = document.getElementById("board");
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");
img.src = 'images/image0.png';
td.appendChild(img);
td.addEventListener("click", function() {
img.src = 'images/image1.png';
});
tr.appendChild(td);
}
board.appendChild(tr);
}
Need to point img child first using document.body.childNodes[0];.
td.addEventListener("click", function() {
var img = this.childNodes[0];
img.src = 'images/image1.png';//use this not img
});
Solution:
var board = document.getElementById("board");
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");
img.src = 'images/image0.png';
td.appendChild(img);
td.addEventListener("click", function() {
var img = this.childNodes[0];
console.log('Source Before Clicking');
console.log(img.src);
img.src = 'images/image1.png';//use this not img
console.log('Source Afer Clicking');
console.log(img.src);
});
tr.appendChild(td);
}
board.appendChild(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">
</div>
Related
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);
}
I would like to open a new page when I tap a cell (TR) in Javascript. I've searched a lot of tutorials online but it doesn't work as well. I hope that someone could help me. Thanks.
Here is my code:
function generateTableBirre()
{
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
row = table.insertRow(-1);
var cell = row.insertCell(-1);
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
cell.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
If you would like to show the table, here is the image:
In the Javascript below the table is created with 2 cells per row. In the first cell you'll find a div with a text paragraph. In the second cell you'll find a div with anchor and image.
Important: an id must be unique so I had to remove lines where duplicate id's were created. If you want to use extra selectors then you can use classList.add("...")
In the css you can style the image width, font, color, etc. For example #dvTable img { max-width: 250px; height: auto; border: 0; }
function generateTableBirre() {
// array containing records
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
// create table
var table = document.createElement('table');
table.classList.add("Birre");
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '20');
// loop through the array and create rows
for (var i = 0; i < birre.length; i++) {
var row = document.createElement('tr');
// loop from 0 to 1 to create two cells on each row
for (var j = 0; j < 2; j++) {
var cell = document.createElement('td');
// give each cell a inner div
var div = document.createElement("div");
div.classList.add("General-Div");
cell.appendChild(div);
// different content in cell 0 and cell 1
if (j == 0) {
// cell 0 contains paragraph
var par = document.createElement("p");
par.innerHTML = birre[i] + ' - ' + price[i];
div.appendChild(par);
} else {
// cell 1 contains image in an anchor
var anch = document.createElement('a');
anch.setAttribute('href', 'Antipasti.html');
div.appendChild(anch);
var img = document.createElement("img");
img.setAttribute('src', 'https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png');
anch.appendChild(img);
}
row.appendChild(cell);
}
table.appendChild(row);
}
// append table in id=dvTable
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
generateTableBirre();
<div id="dvTable">
</div>
try this,
function generateTableBirre() {
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
//var row = table.insertRow(-1);
//var cell = row.insertCell(-1);
var row = document.createElement("tr");
table.appendChild(row);
var cell = document.createElement("td");
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
row.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
I'm trying to add an image to my table for each individual cell using Javascript as part of a Connect4 game that I have to create for my assignment. Could I please get some help with this?
Here's the function that I am trying to add the image in: (the stuff that's been commented out is what I've tried to use but failed
function generateTable()
{
var brd = document.getElementById("board");
var x =document.createElement("IMG");
x.setAttribute("src","block.png");
x.setAttribute("height","10%");
x.setAttribute("width","10%");
x.setAttribute("alt","block.png");
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var maxCol= 7;
var maxRow = 6;
for(var x=0;x<maxRow;x++)
{
var row = document.createElement("tr");
for(var y=0;y<maxCol;y++)
{
var cell = document.createElement("td") ;
/* cell= "<img src='board.png' alt='board' height='10%' width = '10%'>";*/
/* var cellImg= document.createElement("board");
cell.appendChild(cellImg);*/
//var cellText = document.createTextNode("jhgfbcjk");
//cell.appendChild(x);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
/*tbl.setAttribute("border","2");*/
}
Use cell.innerHTML = '<img src="http://placehold.it/40x40?text=IMG" width="20" height="20" />';
function generateTable() {
var brd = document.getElementById("board");
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var maxCol = 7;
var maxRow = 6;
for (var x = 0; x < maxRow; x++) {
var row = document.createElement("tr");
for (var y = 0; y < maxCol; y++) {
var cell = document.createElement("td");
cell.innerHTML = '<img src="http://placehold.it/40x40?text=IMG" width="20" height="20" />';
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
brd.appendChild(tbl);
}
generateTable()
<div id="board"></div>
Within your generateTable() function, try adding:
function generateTable()
{
var whateverrow=document.getElementById("yourId").rows[0];
x.innerHTML="<img src='URL' alt='whatever'/>";
}
This should set the inner HTML of a new cell to a HTML img element.
I want to add an id to the cells, so like row 0/col 0 would have an id of 1, row 0/col 1 would have an id of 2, and etc.
heres my code that im working with:
function init() {
var board = document.getElementById("board");
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");
img.src = 'images/image0.png';
img.id = 'r' + row + 'c' + col;
td.appendChild(img);
td.addEventListener("click", function() {
var img = this.childNodes[0];
img.src = 'images/image1.png';
});
tr.appendChild(td);
}
board.appendChild(tr);
}
You can create and increment an id variable to assign each table cell an ordered numeric identifier:
var board = document.getElementById("board");
var NUM_ROWS = 6;
var NUM_COLS = 6;
var id = 1;
for (row = 0; row < NUM_ROWS; row++) {
var tr = document.createElement("tr");
for (col = 0; col < NUM_COLS; col++) {
var td = document.createElement("td");
td.id = id++;
var img = document.createElement("img");
img.src = 'images/image0.png';
img.id = 'r' + row + 'c' + col;
td.appendChild(img);
td.addEventListener("click", function() {
var img = this.childNodes[0];
// showPicture(img);
console.log(img.id);
});
tr.appendChild(td);
}
board.appendChild(tr);
}
<table id="board"></table>
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.