I'm making a program that generates 2 tables. First has 16 images that represent a menu or options that you can click and then by clicking it you select in. The second table is generated by inputting rows and cells. So the second table is by default blank and each cells is meant to by replaced by an image that you selected in the first table. I've managed to do everything but I don't completley understand how to do the selecting and setting the image. (I assume it has something to do with ids and then onclick()?)
stolpci = window.prompt("vpiši stevilo stolpcov:");
for (i2 = 0; i2 < 1;) {
if (stolpci < 11 || stolpci > 41) {
stolpci = window.prompt("Napačno število. Število mora biti večje od 10 in manjše od 40. Ponovno vpiši stevilo stolpcov:");
} else {
i2++;
}
}
vrstice = window.prompt("vpiši stevilo vrstic:");
for (i2 = 0; i2 < 1;) {
if (vrstice < 6 || vrstice > 11) {
vrstice = window.prompt("Napačno število. Število mora biti večje od 5 in manjše od 11. Ponovno vpiši stevilo vrstic:");
} else {
i2++;
}
}
function generateTable() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let i = 0; i < vrstice; i++) {
const row = document.createElement("tr");
row.id = i;
for (let j = 0; j < stolpci; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(' ');
cell.appendChild(cellText);
row.appendChild(cell);
cell.id = j;
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
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("");
if (nImage > 16) {
nImage = 1;
}
cell.style.backgroundImage = "url('images/sprite" + nImage + ".gif')";
cell.id = nImage;
nImage++;
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
window.onload = () => {
options();
generateTable();
}
table {
border: 1px solid gray;
padding: 0px;
margin: 0px;
border-spacing: 0px;
}
td {
margin: 0px;
padding: 0px;
min-width: 32px;
max-width: 32px;
max-height: 32px;
min-height: 32px;
width: 32px;
height: 32px;
border: 1px solid gray;
background-color: silver;
}
You would need to add click events to each cell. When click you could have another object which you save the 'selected' data to i.e the cell data. You would then need a button which when clicked would move your 'selected' data to the cells in the other table.
I am trying to create two tables and populate them with two randomized arrays. I don't remember how I got to this point but below is a codepen I have. I want to create a table class="side" and a table class="top" and put the random arrays in them. Please forgive me for the messy codes. I have no experience with coding and just want to make something for my students. Thank you.
edit1: cut the codes a little. I want to make a table with 3 cells in a column and another table with 4 cells in a row and randomly populate them with the two emojis array respectively. Can anyone help me with the JS codes?
<table class="top">
1
1
1
</table>
<table class="side">
2222
</table>
UPDATE:
Thanks to everyone for your input and advice. With the examples I was able to understand what my codes was lacking. I've posted it below for viewing and have hide the incomplete codes.
const animals = [
"🐕",
"🐈",
"🐄",
"🐐",
"🐎",
"🐖",
"🐇",
"🦆",
"🐔",
"🐁",
"🐑"
];
const fruits = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
"🍓",
"🍆",
"🥕",
"🥒",
"🫑",
"🧅",
"🍄"
];
function shuffle(a) {
let j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
shuffle(animals);
let t1side = document.getElementsByClassName("tside").item(0);
for (let x = 0; x < 3; x++) {
let tr = document.createElement("tr");
for (let y = 0; y < 1; y++) {
let td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(animals[x * 1 + y]));
}
tr.appendChild(td);
}
t1side.appendChild(tr);
}
shuffle(fruits);
let t2top = document.getElementsByClassName("ttop").item(0);
for (let x = 0; x < 1; x++) {
let tr = document.createElement("tr");
for (let y = 0; y < 4; y++) {
let td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(fruits[x * 1 + y]));
}
tr.appendChild(td);
}
t2top.appendChild(tr);
}
* {
padding: 0;
margin: 0;
}
.top {
top: 0px;
left: 200px;
position: absolute;
}
.side {
top: 100px;
left: 0px;
position: absolute;
}
table.ttop ,table.ttop tr,table.ttop td {
height: 50px;
width: 100px;
padding: 0px;
marging: 0px;
background-color: pink;
font-size: 50px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
table.tside, table.tside tr, table.tside td {
height: 50px;
width: 50px;
padding: 0px;
marging: 0px;
background-color: yellow;
font-size: 80px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
<body>
<style>
</style>
<body>
<div class="top">
<table class="ttop">
</table>
</div>
<div class="side">
<table class="tside">
</table>
</div>
</body>
<script>
</script>
</body>
var spaces2 = [
"🐕",
"🐇",
"🦆",
"🐔",
"🐁",
"🐑"
];
var spaces = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
];
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
shuffle(spaces2);
var tbody = document.getElementsByTagName("tbody").item(0);
for (var x = 0; x < 3; x++) {
var tr = document.createElement("tr");
for (var y = 0; y < 1; y++) {
var td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(spaces2[x * 1 + y]));
}
tr.appendChild(td);
}
tbody.appendChild(tr);
}
shuffle(spaces);
var top = document.getElementsByClassName("top").item(0);
for (var x = 0; x < 1; x++) {
var tr = document.createElement("tr");
for (var y = 0; y < 4; y++) {
var td = document.createElement("td");
{
td.setAttribute("id", "r" + (x + 1) + "d" + (y + 1));
td.appendChild(document.createTextNode(spaces[x * 1 + y]));
}
tr.appendChild(td);
}
tbody.appendChild(tr);
}
* {
padding: 0;
margin: 0;
}
table.top tbody, tr, td {
height: 50px;
width: 50px;
padding: 0px;
marging: 0px;
background-color: none;
font-size: 40px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
table.side tbody, tr, td {
height: 50px;
width: 50px;
padding: 0px;
marging: 0px;
background-color: none;
font-size: 40px;
text-align: center;
border-collapse: collapse;
border: 0px solid none;
}
<body>
<style>
</style>
<body>
<div class="top">
<table id="top">
</table>
<div class="side">
<table id="side">
<tbody></tbody>
</table>
</div>
</body>
<script>
</script>
</body>
You want to generate tables from javaScript using an aYrray as content. Here is a small snippet of the generation of a table.
const spaces = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
"🍓",
"🍆",
"🥕",
"🥒",
"🫑",
"🧅",
"🍄"
];
function loadEvents() {
generateTable(spaces, "container", ["class1", "class2", "class3", "etc"]);
}
function generateTable(dataTable, containerId, classes) {
shuffle(dataTable);
let container = document.getElementById(containerId);
let table = document.createElement("table");
// Add classes to table
for (const clazz of classes) {
table.classList.add(clazz);
}
// Calculate cant of rows and columns
let cantDataRow = 0;
let cantDataCol = 0;
do {
cantDataRow++;
cantDataCol = Math.ceil(dataTable.length / cantDataRow);
} while (dataTable.length / Math.pow(cantDataRow, 2) > 1);
let aux = 0;
for (let i = 0; i < cantDataRow; i++) { // rows
let row = document.createElement("tr");
for (let j = 0; j < cantDataCol; j++) { // columns
let col = document.createElement("td");
col.textContent = dataTable[aux++];
row.appendChild(col); // Add column to row
}
table.appendChild(row); // Add row to table
}
container.appendChild(table); // Add table to container
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
addEventListener("DOMContentLoaded", loadEvents);
table, tr, td{
border: 1px solid black;
border-collapse: collapse;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="container"></div>
<script src="script.js"></script>
</body>
</html>
You would only have to call the function passing it the array with the data of the table, the container of the table and the classes that you want it to contain.
It is not necessary to create the shuffle function twice. It is created only once and can be called infinitely many times. I recommend using let instead of var.
Nice question :-) You only need one loop for each table. I did it with a for loop. I added a function that outputs a random image.
const t1 = document.querySelector('.top');
const t2 = document.querySelector('.side');
const spaces2 = [
"🐕",
"🐇",
"🦆",
"🐔",
"🐁",
"🐑"
];
const spaces = [
"🍇",
"🍊",
"🍑",
"🥝",
"🍈",
"🍉",
"🥭",
"🍎",
];
let tr = document.createElement('tr');
for (let i = 0; i < 3; i++) {
let td = document.createElement('td');
td.innerHTML = getRandomElement(spaces2);
tr.append(td);
}
t1.append(tr);
// t2
for (let i = 0; i < 4; i++) {
let tr = document.createElement('tr');
let td = document.createElement('td');
td.innerHTML = getRandomElement(spaces);
tr.append(td);
t2.append(tr);
}
function getRandomElement(items) {
return items[Math.floor(Math.random()*items.length)];
}
small {
font-size: 16px;
padding-left:5px;
}
table {
}
table td {
border: 2px solid #999;
padding: 5px;
}
<h2>Table 1<small>3 cols and 1 row</small></h2>
<table class="top"></table>
<h2>Table 2<small>1 cols with 4 rows</small></h2>
<table class="side"></table>
Could anyone help me make a multiplication table, 0-10 in an 11x11 table?
I need to use createElement/appendchild. When I use document write, it almost look complete, just miss the placement of the blue columns/rows.
It should look something like this (Only need the numbers, no fancy outline):
This is what I've got so far:
for(var i = 0; i < 1; i++){
var tabell1 = document.createElement("table");
tabell.appendChild(tabell1);
//document.write("<table>");
for(var j = 0; j<11; j++){
var rad = document.createElement("tr");
tabell.appendChild("tr");
//document.write("<tr>");
for(var k = 1; k<=11; k++){
var kolonne = document.createElement("td");
tabell.appendChild(kolonne);
kolonne.innerHTML = k*(j+1);
//document.write("<td>"+ k*(j+1) +"</td>");
}
//document.write("</tr>");
}
//document.write("</table>")
}
<div id="tabell"></div>
You can generate the table using two loops.
You iterate twice from 0 to 10 included.
Use use the value 0 to represent your top row and first column, which hold the numbers to be multiplied. Since the iterator starts at 0, the value will be 0 and you can use that to detect when to add the header class and set the value to your non-zero iterator, either i or j:
const table = document.createElement('table');
for (let i = 0; i <= 10; i++){
const row = document.createElement('tr');
for (let j = 0; j <= 10; j++){
const col = document.createElement('td');
let val = i * j;
if (val === 0) {
val = i || j;
val = val ? val : '';
col.classList.add('header');
}
col.innerHTML = val;
row.appendChild(col);
}
table.appendChild(row);
}
document.body.appendChild(table);
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 3px;
text-align: center;
}
.header {
background: #ccf;
}
The blue border can be obtained by css. See my code. I only changed four lines of loop
function createTables(maxNum,limit){
const table = document.createElement('table');
for(let i = 0;i<maxNum + 1;i++){
const row = document.createElement('tr');
for(let j = 0;j<limit + 1;j++){
const td = document.createElement('td');
//Below four lines are new
if(i === 0 && j === 0) td.innerHTML = '';
else if(i === 0) td.innerHTML = j;
else if(j === 0) td.innerHTML = i;
else td.innerHTML = i*j;
row.appendChild(td);
}
table.appendChild(row)
}
document.body.appendChild(table)
}
createTables(10,15);
table{
border-collapse:collapse;
}
td{
padding:20px;
font-size:25px;
background-color:gray;
border:2px solid black;
text-align:center;
vertical-align:center;
color:white;
}
tr > td:nth-child(1),tr:nth-child(1) > td{
background:blue;
}
I think best to use inserRow and insertCell
Cheers!
for (var i = 0; i < 1; i++) {
var tabell1 = document.createElement("table");
tabell.appendChild(tabell1);
for (var j = 0; j < 11; j++) {
var row = tabell1.insertRow(j);
for (var k = 0; k <= 10; k++) {
var cell = row.insertCell(k);
if (j == 0 && k == 0) {
//if first row and first column do nothing
} else if (j == 0) {
//else if first row
cell.innerHTML = k * (j + 1);
} else if (k == 0) {
//else if first column
cell.innerHTML = j;
} else {
//else multiply
cell.innerHTML = k * (j);
}
}
}
}
<div id="tabell"></div>
My homework was to create a scipt that connects two marked cells of a table. My solution works fine, but the result line is a bit disproportionate.
As you can see, the last row is 4-cells long while all other rows are 3-cells long. But I'd like the middle part of a line to be the longest. Like this:
How to get the desired result and not make the code too complicated. The code itself:
function connectThem() {
if (markedCells.length == 2) {
y_distance = markedCells[0][0] - markedCells[1][0];
y_distance = Math.abs(y_distance) + 1; // vertial distance
x_distance = markedCells[0][1] - markedCells[1][1];
x_distance = Math.abs(x_distance) + 1; // horizontal distance
if (x_distance > y_distance) { // if horizontal distance greater than vertical distance
x_distance -= 0;
alert("horizontal connection");
totalRows = y_distance;
for (var row = 0; row < y_distance; row++) {
thisRowLength = Math.floor(x_distance / totalRows);
for (var c = 0; c < thisRowLength; c++) {
document.getElementById('cell-' + markedCells[0][0] + '-' + markedCells[0][1]).style.backgroundColor = "red";
markedCells[0][1] = parseInt(markedCells[0][1]) + 1;
}
markedCells[0][0] = parseInt(markedCells[0][0]) + 1;
totalRows -= 1; // vertical remaining
x_distance -= thisRowLength; // horizontal remaining
}
} else {
y_distance -= 0;
alert("vertical or horizontal connection");
totalCols = x_distance;
for (var col = 0; col < x_distance; col++) {
thisColLength = Math.floor(y_distance / totalCols);
for (var r = 0; r < thisColLength; r++) {
document.getElementById('cell-' + markedCells[0][0] + '-' + markedCells[0][1]).style.backgroundColor = "red";
markedCells[0][0] = parseInt(markedCells[0][0]) + 1;
}
markedCells[0][1] = parseInt(markedCells[0][1]) + 1;
totalCols -= 1;
y_distance -= thisColLength;
}
}
alert("x distance: " + x_distance + " y distance: " + y_distance);
} else {
alert("Can't connect " + markedCells.length + " cells together :-(")
}
}
var htmlElements = ""; // storing the whole table here
for (var r = 1; r < 41; r++) { // creating the table row by row
htmlElements += '<tr>';
for (var c = 1; c < 61; c++) { // and column by column
htmlElements += '<td class="tCell white" id="cell-' + r.toString() + '-' + c.toString() + '"></td>';
}
htmlElements += '</tr>'
}
var theTable = document.getElementById("tab");
theTable.innerHTML = htmlElements;
var allTableCells = document.querySelectorAll("td"); // adding all cells to an array
var markedCells = [] // storing marked cells here
for (var i = 0; i < allTableCells.length; i++) {
allTableCells[i].addEventListener("click", function() { // when click any cell
let stringID = this.id.split('-');
if (this.className == "tCell white") {
this.className = "tCell red";
markedCells.push([stringID[1], stringID[2]]);
} else {
this.className = "tCell white";
let index = markedCells.indexOf([stringID[1], stringID[2]]);
markedCells.splice(index, 1);
}
console.log(markedCells);
});
}
body {
background-color: #333;
}
#workspace {
position: absolute;
width: 900px;
height: 600px;
background-color: whitesmoke;
top: 50%;
left: 50%;
margin-left: -450px;
margin-top: -300px;
}
table,
tr,
td {
border: 1px solid black;
border-collapse: collapse;
padding: 0;
}
table {
width: 900px;
height: 600px;
}
.red {
background: red;
color: white;
}
.white {
background: white;
color: black;
}
#btn {
position: absolute;
width: 100px;
top: 50px;
left: 50%;
margin-left: -50px;
}
<div id="workspace">
<table id="tab">
</table>
</div>
<button id="btn" onclick="connectThem()">Connect!</button>
I am making Snake and Ladder game using JavaScript. I want to insert the game board generated from the create Board(dimension) function into a div, but [object Object] is what is appears.
var gameBoard = {
createBoard: function(dimension) {
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
document.body.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
len,
cells,
real,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
len = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < len; i++) {
if (odd == true) {
real = --size + rowCounter - i;
} else {
real = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = real;
rowCounter++;
}
}
return gameBoard;
}
};
//board.createBoard(10);
document.getElementById("div1").innerHTML = gameBoard.createBoard(10);
td {
border-radius: 10px;
width: 55px;
height: 55px;
line-height: 55px;
text-align: center;
border: 0px solid #FFFFFF;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
td:hover {
background: LightCyan !important;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="StyleSheet1.css" rel="stylesheet" />
</head>
<body>
<div id="div1"></div>
<script src="JavaScript1.js"></script>
</body>
</html>
I need help on how to solve this problem. Thanks in advance.
All you wanted was the gameBoard to be appended to the div#div1, correct?
Added mount parameter to createBoard() function
var mount is a selector that will be referenced as the element to which the table element will be appended to.
Comments accompany changes in the code.
I added a border around #div1 to show that the gameBoard has been successfully appended to #div1
var gameBoard = { //===============▼---▼====[This is can be any selector]
createBoard: function(dimension, mount) {
//==▼------------------------------------▼====[Object mount]
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
//▼---------------------▼====[Object table append to Object mount]
mount.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
len,
cells,
real,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
len = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < len; i++) {
if (odd == true) {
real = --size + rowCounter - i;
} else {
real = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = real;
rowCounter++;
}
}
return gameBoard;
}
};
/*board.createBoard(10);
[On window load call createBoard with 10 rows and mount it to #div1]
▼----------------------------▼===============================*/
window.onload = (function(e) {
gameBoard.createBoard(10, '#div1');
});
td {
border-radius: 10px;
width: 55px;
height: 55px;
line-height: 55px;
text-align: center;
border: 0px solid #FFFFFF;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
td:hover {
background: LightCyan !important;
cursor: pointer;
}
#div1 {
border: 3px inset #0FF;
border-radius: 10px;
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="div1"></div>
</body>
</html>