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.
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);
}
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.
I want to delete a row from a table created by JavaScript. i tried the code from different post on this page but doesn't solve it.
function value_pass()
{
var Delete = document.createElement("input");
Delete.type="button";
Delete.name = "del"
Delete.value = "Delete";
Delete.onclick = function(o)
{
var r = o.parentElement.parentElement;
document.getElementById("table").deleteRow(r.rowIndex);
}
var order_no = document.getElementById("Order_no");
var quantity = document.getElementById("quantity");
var type = document.getElementById("Recipe");
var recipe = type.options[type.selectedIndex].text;
var body1 = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute("id","table");
var tblbody = document.createElement("tbody");
tbl.setAttribute("border","2");
var col = document.createElement("td");
for (var j = 0; j < 1; j++)
{
var rows = document.createElement("tr");
for (var i = 0; i < 4; i++)
{
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
var col5 = document.createElement("td");
var col1text = document.createTextNode(order_no.value);
var col2text = document.createTextNode(recipe);
var col3text = document.createTextNode(quantity.value);
var col4text = document.createTextNode();
//also want to put checked values in table row
}
col1.setAttribute("width","150");
col2.setAttribute("width","150");
col3.setAttribute("width","150");
col4.setAttribute("width","150");
col1.appendChild(col1text);
col2.appendChild(col2text);
col3.appendChild(col3text);
col4.appendChild(col4text);
col5.appendChild(Delete);
rows.appendChild(col1);
rows.appendChild(col2);
rows.appendChild(col3);
rows.appendChild(col4);
rows.appendChild(col5);
tblbody.appendChild(rows);
} tbl.appendChild(tblbody);
body1.appendChild(tbl);
}
The function will be called by a button in HTML
its an order form that
and also want to know about the checked values of checkbox to put in the table row.
You can use :
document.getElementById("myTable").deleteRow(0); //Where 0 is your row.
Explained : http://www.w3schools.com/jsref/met_table_deleterow.asp
Edit:
To delete the current row, set this on your button: onclick="deleteRow(this), with the following code in that function:
function deleteRow(t)
{
var row = t.parentNode.parentNode;
document.getElementById("myTable").deleteRow(row.rowIndex);
console.log(row);
}
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