Multiplication Table in Javascript space between numbers? - javascript

var numbers = "";
for (var i = 1; i <= 13; i++){
for (var j = 1; j<= 13; j++){
numbers += (i*j) + '';
}
numbers += '<br>';
}
element.innerHTML = numbers;
how can i make a space between every number?
example:

You can use <table> for that to structure your text:
let numbers = "<tbody>";
for (let i = 1; i <= 13; i++){
numbers += '</tr>';
for (let j = 1; j<= 13; j++){
numbers += `<td>${i*j}</td>`;
}
numbers += '</tr>';
}
numbers += "</tbody>"
const element = document.querySelector("#element");
element.innerHTML = numbers;
td {
text-align: right;
width: 2em;
}
<table id="element">

You can use grid approach with some CSS variables to make cell elements, for more details see comments in Code snippet:
Also you could render headings of the cells.
const gridSize = 13;
// get grid element
const grid = document.querySelector('.grid');
// create temporary wrapper
const fragmentWrapper = document.createDocumentFragment();
const renderTop = () => {
for (var i = 0; i <= gridSize; i++) {
if (i === 0) {
// render mult char
renderCell('x');
continue;
}
renderCell(i, true);
}
}
const renderGrid = () => {
// append cells to wrapper
for (var i = 1; i <= gridSize; i++) {
for (var j = 0; j <= gridSize; j++) {
if (j === 0) {
// render heading cell
const num = i;
renderCell(num, true);
continue;
}
// render default cell
const num = i * j;
renderCell(num);
}
}
}
const renderCell = (num, select = false) => {
// create temporary cell
const cell = document.createElement('div');
cell.className = 'cell';
// if requested to highligh cell
select && cell.classList.add('select');
cell.innerText = `${ num }`;
// add cell to grid
fragmentWrapper.append(cell);
}
renderTop();
renderGrid();
// set grid size
grid.style.setProperty('--grid-size', gridSize);
// render grid
grid.append(fragmentWrapper);
.grid {
display: grid;
grid-template-columns: repeat(calc(var(--grid-size) + 1), 1fr);
/* using CSS grid size (set in JS) */
gap: .25rem;
}
.cell {
display: flex;
align-items: center;
/* align content */
justify-content: center;
/* align content */
aspect-ratio: 1/1;
/* make cell square */
border: 1px solid #d4d4d4;
/* show cell borders */
}
.cell.select {
background-color: tomato;
color: white;
font-weight: bold;
}
<div class="grid"></div>

You could be ambitious and, like David said, use CSS to take the weight of how the data is meant to be displayed. I've used CSS grid in this example which means you only need to have one loop, and the CSS takes care of the rest.
const arr = [];
const size = 13;
const limit = size * size;
// Push an HTML template string into
// the array
for (var i = 1; i <= limit; i++) {
arr.push(`<div>${i}</div>`);
}
// Add the joined array (it makes an HTML string
// to the element with the `grid` class
const grid = document.querySelector('.grid');
grid.innerHTML = arr.join('');
.grid {
display: grid;
grid-template-columns: repeat(13, 30px);
grid-gap: 0.2em;
}
.grid div {
border: 1px solid #cdcdcd;
font-size: 0.8em;
background-color: #efefef;
text-align: center;
padding: 0.5em 0;
}
<div class="grid"></div>
Additional documentation
Template/string literals
Edit: you can even create a function that will accept a number, and, using CSS variables, the function will work out the size of the grid required and return the HTML.
function createGrid(columns) {
const arr = [];
const grid = columns * columns;
document.documentElement.style.setProperty('--columns', columns)
// Push an HTML template string into
// the array
for (var i = 1; i <= grid; i++) {
arr.push(`<div>${i}</div>`);
}
return arr.join('');
}
const grid = document.querySelector('.grid');
grid.innerHTML = createGrid(5);
:root {
--columns: 13;
}
.grid {
display: grid;
grid-template-columns: repeat(var(--columns), 40px);
grid-gap: 0.2em;
}
.grid div {
border: 1px solid #cdcdcd;
font-size: 0.8em;
background-color: #efefef;
text-align: center;
padding: 0.5em 0;
}
<div class="grid"></div>

Please use like this
<!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">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
</style>
</head>
<body>
<div id="test" style="width:800px;height: 350px; border: 1px solid sandybrown;">
</div>
<script>
var element = document.getElementById("test");
var html = "<table>";
for (var i = 1; i <= 10; i++){
html += "<tr>";
for (var j = 1; j<= 10; j++){
html += "<td>"+ (i*j) +"</td>";
}
html += '</tr> ';
}
html += "</table>";
element.innerHTML = html;
</script>
</body>
</html>

Related

javascript/html flowing tables on to new line

I have some javascript that generates a variable number of tables. Currently, these tables are displayed in a list down the page:
However, this means that, if there are more than about four tables, the bottom ones are not visible and I need to scroll, meaning I can't see the top ones.
So, what I would like to do is to somehow 'flow' the tables (I can make them narrower) across the page and then on to a new line. So, if I have five tables, then I have (say) two columns on the page, with heats 1, 3 and 5 appearing in column 1; and heats 2 and 4 in column 2.
Here is the section of the code that deals with this:
numGroups = groups.length;
for (var g = 0; g < numGroups; g++)
{
// Create a new table for each group
var t=document.createElement('table');
t.style.borderCollapse = 'collapse';
t.style.cellPadding = '5px';
// Create table header showing group number
var caption = document.createElement( "caption" );
caption.style.textAlign = 'left';
caption.style.paddingTop = '10px';
caption.style.color = "white";
thisGroup = (g+1);
caption.appendChild(document.createTextNode("Group "+thisGroup));
t.appendChild(caption);
var headers = ["Pos", "Driver", "Score", "Best Lap"];
for (var i = 0; i < headers.length; i++)
{
var th = document.createElement( "th" );
th.style.color = headerColour;
th.style.border= theBorderWidth + borderColour;
th.appendChild(document.createTextNode(headers[i]));
t.appendChild(th);
}
// Create a table record for each driver in the group
numGroupDrivers = groups[g].length
for (var k = 0; k <numGroupDrivers; k++) //run through each of the drivers in the heat.
{
var tr=document.createElement('tr'); //create variable 'tr' to create a table row
tr.style.backgroundColor = "transparent";
tr.style.color = textColour;
var name = groups[g][k]; //variable name = nickname
if (name == null && config.d) { //if name isn't blank and this is a digital race...
continue;
}
// Create column for position
var tdPos=document.createElement('td'); //create variable 'tdPos' to create a table cell with data
tdPos.style.width='50px';
tdPos.style.textAlign='center';
tdPos.style.border=theBorderWidth + borderColour;
tdPos.appendChild(document.createTextNode(k+1)); //go through the table in order setting tdPos to row number
tr.appendChild(tdPos); //add tdPos to table record
var tdName=document.createElement('td'); //create variable 'tdName' to create a table cell with data
tdName.style.width='250px';
tdName.style.textAlign='center';
tdName.style.border=theBorderWidth + borderColour;
tdName.appendChild(document.createTextNode(name));
tr.appendChild(tdName);
//Create column for score
var tdScore=document.createElement('td');
tdScore.style.width='80px';
tdScore.style.textAlign='center';
tdScore.style.border=theBorderWidth + borderColour;
for (var l = 0; l <scoreArray.length; l++)
{
if (groups[g][k] == scoreArray[l][0])
{
if (scoreArray[l] == 0)
{
tdScore.appendChild(document.createTextNode("--"));
} else
{
tdScore.appendChild(document.createTextNode(scoreArray[l][1]));
}
}
tr.appendChild(tdScore);
t.appendChild(tr);
}
//Create column for best lap
var tdTime=document.createElement('td');
tdTime.style.width='120px';
tdTime.style.textAlign='center';
tdTime.style.border=theBorderWidth + borderColour;
for (var l = 0; l <scoreArray.length; l++)
{
if (groups[g][k] == scoreArray[l][0])
{
if (scoreArray[l][2] == -1)
{
tdTime.appendChild(document.createTextNode("--"));
} else
{
tdTime.appendChild(document.createTextNode(scoreArray[l][2]));
}
}
tr.appendChild(tdTime);
t.appendChild(tr);
}
}
groupTables[g] = t;
}
Any help gratefully received!
Thanks,
Connal
This isn't a direct answer to your question.
In spirit, though, I think it's the best answer you'll get...
Learn css-flex. JavaScript as presentational layer will be brittle and is not the optimal place for it anyway. On a large screen and mouse (i.e. a laptop or desktop but not a phone) take a look at MDN's tutorial on flex. You'll be able to get what you want in a way that
degrades nicely,
is faster,
is less reliant on platform/browser,
already debugged,
helps you learn another browser-native technology that you'll have on your tool belt tomorrow
might possibly be more accessible to screen readers and other aids for the visually impaired,
flows better, and smoothly, when someone resizes their screen or changes the font size.
Bonus: Anyone in the future maintaining your code (including and especially youself) will find it much easier.
I had resisted learning flex for years, choosing instead to keep moving with my then-current projects as fast as I could. I regret that. I'm screwed; I'll never get that time back. My best way to pay it forward is to highly recommend you give it a shot.
If anyone has another great link for intro to CSS flex that they recommend, please comment.
So, if you adopt this approach, then instead of a TABLE tag contains TR tags containing TD tags, you'll need to generate a DIV (or SECTION) tag that has a specific class attribute, containing a DIV (or ARTICLE) tag per "row", which contain DIV tags per "cell", and after that it's all CSS.
If you're still not convinced, try looking at CSS Zen Garden for examples of how, if you organize your HTML to tell the browser only "what the information is" and leave "what it should look like" to CSS, both tasks are easier to accomplish.
As per my comment, You might set width: 45%; display: inline-table to your tables:
var groups = [
['John', 'Sam', 'Peter'],
['John', 'Sam', 'Peter'],
['John', 'Sam', 'Peter'],
['John', 'Sam', 'Peter'],
['John', 'Sam', 'Peter'],
],
scoreArray = [
[],
[],
[],
[],
[]
],
g = 0,
headerColour = 'gold',
textColour = 'black',
borderColour = 'black',
theBorderWidth = 'solid 1px ';
groups.forEach(idx => {
// Create a new table for each group
var t = document.createElement('table');
t.style.width = '45%';
t.style.display = 'inline-table';
t.style.marginRight = '2%';
t.style.borderCollapse = 'collapse';
t.style.cellPadding = '5px';
// Create table header showing group number
var caption = document.createElement("caption");
caption.style.textAlign = 'left';
caption.style.paddingTop = '10px';
caption.style.color = "white";
thisGroup = (g + 1);
caption.appendChild(document.createTextNode("Group " + thisGroup));
t.appendChild(caption);
var headers = ["Pos", "Driver", "Score", "Best Lap"];
for (var i = 0; i < headers.length; i++) {
var th = document.createElement("th");
th.style.color = headerColour;
th.style.border = theBorderWidth + borderColour;
th.appendChild(document.createTextNode(headers[i]));
t.appendChild(th);
}
// Create a table record for each driver in the group
numGroupDrivers = groups[g].length
for (var k = 0; k < numGroupDrivers; k++) //run through each of the drivers in the heat.
{
var tr = document.createElement('tr'); //create variable 'tr' to create a table row
tr.style.backgroundColor = "transparent";
tr.style.color = textColour;
var name = groups[g][k]; //variable name = nickname
if (name == null && config.d) { //if name isn't blank and this is a digital race...
continue;
}
// Create column for position
var tdPos = document.createElement('td'); //create variable 'tdPos' to create a table cell with data
tdPos.style.width = '50px';
tdPos.style.textAlign = 'center';
tdPos.style.border = theBorderWidth + borderColour;
tdPos.appendChild(document.createTextNode(k + 1)); //go through the table in order setting tdPos to row number
tr.appendChild(tdPos); //add tdPos to table record
var tdName = document.createElement('td'); //create variable 'tdName' to create a table cell with data
tdName.style.width = '250px';
tdName.style.textAlign = 'center';
tdName.style.border = theBorderWidth + borderColour;
tdName.appendChild(document.createTextNode(name));
tr.appendChild(tdName);
//Create column for score
var tdScore = document.createElement('td');
tdScore.style.width = '80px';
tdScore.style.textAlign = 'center';
tdScore.style.border = theBorderWidth + borderColour;
for (var l = 0; l < scoreArray.length; l++) {
if (groups[g][k] == scoreArray[l][0]) {
if (scoreArray[l] == 0) {
tdScore.appendChild(document.createTextNode("--"));
} else {
tdScore.appendChild(document.createTextNode(scoreArray[l][1]));
}
}
tr.appendChild(tdScore);
t.appendChild(tr);
}
//Create column for best lap
var tdTime = document.createElement('td');
tdTime.style.width = '120px';
tdTime.style.textAlign = 'center';
tdTime.style.border = theBorderWidth + borderColour;
for (var l = 0; l < scoreArray.length; l++) {
if (groups[g][k] == scoreArray[l][0]) {
if (scoreArray[l][2] == -1) {
tdTime.appendChild(document.createTextNode("--"));
} else {
tdTime.appendChild(document.createTextNode(scoreArray[l][2]));
}
}
tr.appendChild(tdTime);
t.appendChild(tr);
}
}
document.body.appendChild(t);
})
Use CSS with an external stylesheet and/or a <style> tag at the bottom of the <head>. You can unclutter the JavaScript by removing all of the expressions with the .style property. Use .class to apply CSS styles to the tags. In the example below, are 7 tables. When there are 5 or less tables, they have width: 100%. When there are more than 5 tables all tables are given the .half class which decreases their widths to 50%. The following styles will automatically arrange the tables in 2 columns when they have class .half:
main { display: flex; flex-flow: row wrap; justify-content: flex-start;
align-items: center;...}
/* Flexbox properties will arrange the tables in two columns when
there are more than 5 of them (because .half will be added to
each table */
.half { width: 50%; }
This flow control statement is responsible for the class change:
if (qty > 5) {
tables.forEach(t => t.classList.add('half'));
} else {
tables.forEach(t => t.classList.remove('half'));
}
Also, it's important that you have full control of the tables, in the example, it fetch()es data from a test server to create as many tables as the qty parameter dictates (in example, it's heats = 7). Normally table column widths are determined by content which makes them sporadically unseemly (especially with dynamic content). table-layout: fixed allows you to set the widths of the columns by adding explicit widths directly to the <th> (or the top <td> if <th> are not present):
table { table-layout: fixed; ...}
BTW, the Total Time does not coincide with Position (ie. lowest Total Time should be matched with Position: 1). If you want to sort the columns you'll need to start another question.
<!DOCTYPE html>
<html lang="en">
<head>
<title>NASCAR HEAT</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
*, *::before, *::after { box-sizing: border-box; }
:root { font: 1ch/1 'Segoe UI'; }
html, body { width: 100%; min-height: 100%; margin: 0; padding: 0; }
body { font-size: 2ch; color: white; background: linear-gradient(to bottom, #85a4e5 13%,#053cbd 66%); }
main { display: flex; flex-flow: row wrap; justify-content: flex-start; align-items: center; width: 100%; height: 100%; margin: 0 auto; }
table { table-layout: fixed; width: 100%; border-collapse: collapse; border: 1px solid white; }
caption { font-size: 1.35rem; font-weight: 900; text-align: left; }
th, td { border: 1px solid white; text-align: center; }
th:nth-of-type(2), td:nth-of-type(2) { text-align: left; }
th { font-size: 1.25rem; overflow: hidden; }
td { font-size: 1.15rem; }
th:first-of-type { width: 5%; }
th:nth-of-type(2) { width: 55%; }
th:nth-of-type(3) { width: 15%; }
th:nth-of-type(4) { width: 15%; }
th:last-of-type { width: 15%; }
.half { width: 50%; }
</style>
</head>
<body>
<main></main>
<script>
let heats = 7;
function buildTables(selector, qty = 1) {
const headers = ['Position', 'Driver', 'Average Lap', 'Best Lap', 'Total Time'];
const base = document.querySelector(selector) || document.body;
for (let i = 0; i < qty; i++) {
let t = document.createElement('table');
let tB = document.createElement('tbody');
let cap = t.createCaption();
cap.textContent = `Heat ${i + 1}`;
t.append(tB);
let tH = t.createTHead();
let hRow = tH.insertRow();
for (let j = 0; j < 5; j++) {
hRow.insertCell().outerHTML = `<th>${headers[j]}</th>`;
}
base.append(t);
}
const tables = [...document.querySelectorAll('table')];
for (let k = 0; k < qty; k++) {
fetch('https://my.api.mockaroo.com/nascar.json?key=3634fcf0').then((res) => res.json()).then(res => {
let row;
for (let r in res) {
row = `<tr>
<td>${res[r].Position}</td>
<td>${res[r].Driver}</td>
<td>${res[r]['Average Lap']}</td>
<td>${res[r]['Best Lap']}</td>
<td>${res[r]['Total Time']}</td>
</tr>`;
tables[k].tBodies[0].insertAdjacentHTML('beforeEnd', row);
}
});
}
if (qty > 5) {
tables.forEach(t => t.classList.add('half'));
} else {
tables.forEach(t => t.classList.remove('half'));
}
};
buildTables('main', heats);
</script>
</body>
</html>

It is possible to create two table with js?

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>

Why with "array[row][col]= usedspace;" cannot increase specific columns and rows depending on the increse each variable (row or column)?

I am Michael and I am new to this forum.
What I want to ask is how through Java Script to make a character 'O' follow your character 'X' in a '.' that is a 20*20 array, but where 'X' pass '.' is replaced with 'O'.
E.g. increase some way the counters inside the if statement that relies in the for loops of row and column of "array a" ?
function start()
{
document.getElementById("wrapper").style="visibility:hidden";
var optionOne = document.getElementById("optionOne");
var display = "";
var txt1 = document.getElementById("txt1");
var mtxt1 = parseInt(txt1.value);
if (mtxt1 == 1)
{
display += "<p>Pen is currently NOT DRAWING</p>";
document.getElementById("wrapper").style="visibility:display";
}
else if (mtxt1 == 2)
{
display += "<p>Pen is DRAWING</p>";
document.getElementById("wrapper").style="visibility:display";
}
optionOne.innerHTML = display;
var button = document.getElementById("getbutton");
button.addEventListener("click",start,false );
//var displaygmb = document.getElementById("displaygmb");
//displaygmb.addEventListener("click", displaygameboard("Gameboard",array,length,arraydisplay),false );
var button2 = document.getElementById("get2button");
button2.addEventListener("click",option2(button2,mtxt1),false );
}
function option2(buttonn,symbolinput)
{
var input = symbolinput;
var usedspace = "O";
var turtle = "X";
var gameboardSymbol = ".";
var clickcountt = buttonn;
var count6 = 1;
var count5 = 1;
var count3 = 1;
var count4 = 1;
var display = "";
clickcountt.onclick = function() {
var optiontwo = document.getElementById("optiontwo");
var display2 = "";
var txt2 = document.getElementById("txt2");
var mtxt2 = parseInt(txt2.value);
if (mtxt2 == 6)
{
count6 += 1;
display2 += "<p>Turtle is moving "+count6+" places down</p>";
}
else if (mtxt2 == 5)
{
count6 -=1;
count5 +=1;
display2 += "<p>Turtle is moving "+count6+" places up</p>";
}
else if (mtxt2 == 3)
{
count3 += 1;
display2 += "<p>Turtle is moving "+count3+" places to the right</p>";
}
else if (mtxt2 == 4)
{
count3 -=1
count4 += 1;
display2 += "<p>Turtle is moving "+count3+" places to the left</p>";
}
optiontwo.innerHTML = display2;
var gameboardsize = 20;
var arraydisplay = document.getElementById("arraydisplay");
var array = new Array (gameboardsize);
var length = array.length;
for (var i = 0; i <= length; i++ )
{
array[i] = new Array(gameboardsize);
}
var arraydisplay = document.getElementById("arraydisplay");
var displaygbd = "<table id=gameb align=center><thead><th>"+"Gameboard"+"</th></thead><tbody>";
for (var row = 1; row <= length; row++)
{
//three += 1;
displaygbd += "<tr>";
for (var col = 1; col <= length; col++)
{
if (input == 1){
//four += 1;
if (((row ==count6)&&(col ==count3)))
{
array[row][col]= turtle;
}
else {
array[row][col]=gameboardSymbol;
}
}
//----------------------------
else if(input == 2)
{
if (((row == count6)&&(col ==count3)))
{
array[row][col]= turtle;
}
/*how to make 'O' follow 'X' by ibncrease the appropriate counter in the if below?*/
else if (((row <= count6)&&(col <=count3)))
{
array[row][col]= usedspace;
}
else if ((((row >= count6)||(col >= count3))))
{
array[row][col]=gameboardSymbol;
}
}//end else if
//----------------------------
displaygbd += "<th>"+array[row][col]+"\xa0"+"</th>";
}
displaygbd += "</tr>";
}
displaygbd += "</tbody></table>";
arraydisplay.innerHTML = displaygbd;
}//end clickout function
}
window.addEventListener("load",start,false);
#charset "ISO-8859-1";
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 30%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers thead th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
#customers tbody th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: white;
color: black;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Initializing an array</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src ="tutle.js"></script>
</head>
<body>
select your first option
<input id ="txt1" type="text">
<input id = "getbutton" type ="button" value = "your option">
<div id = "optionOne"></div>
<br/>
<div id = "arraydisplay"></div>
<div id="wrapper" >
select your second option
<input id ="txt2" type="text">
<input id = "get2button" type ="button" value = "your option">
<div id = "optiontwo"></div>
</div>
<div id = "counters"></div>
<div id = "optionthree"></div>
</body>
</html>
Sharing a possible solution.
This should get you more than started.
Try running this here itself and let me know if this is ok. I'll add an explanation if required.
The 2 inputs receive the new location of 'X'. text1 receives row number and text2 receives column number. On button press, the corresponding dimension is updated.
var button1 = document.getElementById('getbutton');
var button2 = document.getElementById('get2button');
var textbox1 = document.getElementById('txt1');
var textbox2 = document.getElementById('txt2');
var gridX = 20;//table size length wise
var gridY = 20;//table size width wise
var arrayContainer = document.getElementById('arraydisplay');
var currentX = 1;//initial positions
var currentY = 1;
function init() {
var myTable = document.createElement('table');
myTable.setAttribute("id", "customers");
arrayContainer.appendChild(myTable);
//Creating initial grid
for(var i=0; i<gridX; i++) {
var row = document.createElement('tr');
for(var j=0; j<gridY; j++) {
var text = document.createTextNode('.');
var column = document.createElement('td');
column.appendChild(text);
row.appendChild(column);
}
myTable.appendChild(row);
}
//Setting initial value
document.getElementsByTagName('tr')[currentX-1].getElementsByTagName('td')[currentY-1].innerText = 'X';
}
init();
button1.onclick = clicked;
function clicked() {//1st position changed
var newX = parseInt(textbox1.value);
var newY = parseInt(textbox2.value);
moveTo(newX, newY);
}
button2.onclick = clicked;
function moveTo(newX, newY) {
//Setting old value to 'O'
var char = 'O'
if(newX == 1)
char = '.';
document.getElementsByTagName('tr')[currentX-1].getElementsByTagName('td')[currentY-1].innerText = char;
//Setting new location with 'X'
document.getElementsByTagName('tr')[newX-1].getElementsByTagName('td')[newY-1].innerText = 'X';
//Updating current location of 'X' for future use.
currentX = newX;
currentY = newY;
}
#charset "ISO-8859-1";
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 30%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers thead th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #4CAF50;
color: white;
}
#customers tbody th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: white;
color: black;
text-align:center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Initializing an array</title>
<link rel="stylesheet" type="text/css" href="style.css">
<!-- <script src ="turtle.js"></script> -->
</head>
<body>
select your first option
<input id ="txt1" type="text">
<input id = "getbutton" type ="button" value = "your option">
<div id = "optionOne"></div>
<div id="wrapper" >
select your second option
<input id ="txt2" type="text">
<input id = "get2button" type ="button" value = "your option">
<div id = "optiontwo"></div>
</div>
<div id = "counters"></div>
<div id = "optionthree"></div>
<br>
<div id = "arraydisplay"></div>
</body>
<script src ="turtle.js"></script>
</html>

Single Player mode in Tic-tac-toe

I am trying to create a one-player tic-tac-toe game using JavaScript. Following is the code for JavaScript, CSS, and HTML respectively:
const grid = [];
const GRID_LENGTH = 3;
let turn = 'X';
function initializeGrid() {
for (let colIdx = 0; colIdx < GRID_LENGTH; colIdx++) {
const tempArray = [];
for (let rowidx = 0; rowidx < GRID_LENGTH; rowidx++) {
tempArray.push(0);
}
grid.push(tempArray);
}
}
function getRowBoxes(colIdx) {
let rowDivs = '';
for (let rowIdx = 0; rowIdx < GRID_LENGTH; rowIdx++) {
let additionalClass = 'darkBackground';
let content = '';
const sum = colIdx + rowIdx;
if (sum % 2 === 0) {
additionalClass = 'lightBackground'
}
const gridValue = grid[colIdx][rowIdx];
if (gridValue === 1) {
content = '<span class="cross">X</span>';
} else if (gridValue === 2) {
content = '<span class="cross">O</span>';
}
rowDivs = rowDivs + '<div colIdx="' + colIdx + '" rowIdx="' + rowIdx + '" class="box ' +
additionalClass + '">' + content + '</div>';
}
return rowDivs;
}
function getColumns() {
let columnDivs = '';
for (let colIdx = 0; colIdx < GRID_LENGTH; colIdx++) {
let coldiv = getRowBoxes(colIdx);
coldiv = '<div class="rowStyle">' + coldiv + '</div>';
columnDivs = columnDivs + coldiv;
}
return columnDivs;
}
function renderMainGrid() {
const parent = document.getElementById("grid");
const columnDivs = getColumns();
parent.innerHTML = '<div class="columnsStyle">' + columnDivs + '</div>';
}
function onBoxClick() {
var rowIdx = this.getAttribute("rowIdx");
var colIdx = this.getAttribute("colIdx");
let newValue = 1;
grid[colIdx][rowIdx] = newValue;
renderMainGrid();
addClickHandlers();
}
function addClickHandlers() {
var boxes = document.getElementsByClassName("box");
for (var idx = 0; idx < boxes.length; idx++) {
boxes[idx].addEventListener('click', onBoxClick, false);
}
}
initializeGrid();
renderMainGrid();
addClickHandlers();
.parentTop {
display: flex;
align-items: center;
justify-content: center;
}
.gridTop {
border-color: "#f44336";
border: '1px solid red';
display: flex;
flex-direction: column;
}
.lightBackground {
background-color: 00FFFF
}
.columnsStyle {
display: flex;
flex-direction: column;
}
.rowStyle {
display: flex;
}
.darkBackground {
background-color: F0FFFF
}
.box {
width: 100;
height: 100;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}
.header {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 100px;
}
.cross {
color: #f90;
font-size: 2.5em;
border-radius: 5px;
line-height: 100px;
}
<div class="header">
<h1> Tic Tac Toe</h1>
</div>
<div class="parentTop">
<div class="gridTop">
<div id="grid">
</div>
</div>
</div>
<script type="text/javascript" src="./index.js"></script>
<link rel="stylesheet" href="./index.css">
Here box represents one placeholder for either X or a 0.
We have a 2D array to represent the arrangement of X or O is a grid
0 -> empty box
1 -> box with X
2 -> box with O
User is playing with Computer so every alternate move should be by Computer
X -> player
O -> Computer
I am not able wrap my head around the implementation of the algorithm used for computer (Min-max algorithm is one) in code.
traverse it in a loop as column first, and row and then diagonal these are three cases where you have to check consecutive user inputs if first two consecutive user inputs found in any of above case then your program have put their value as third one as apponent

How to insert object in div using JavaScript?

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>

Categories