I've dynamically created an HTML table with a specified number of rows and columns. The next step is to highlight the cells in the bottom left half of the table with a light red color, forming a triangle pattern similar to the one shown in this link.
Below is the code I used to generate the table:
//Function for handling events
function print_table() {
let _tblRows, _tblCols, tblElm, rowElm, colElm, randNmbrArray, _tblDiv, _randNmbrAvg, avgElm;
_tblRows = document.getElementById('rows').value;
_tblCols = document.getElementById('cols').value;
randNmbrArray = [];
_tblDiv = document.getElementById('my_table');
avgElm = document.getElementById('average');
if (_tblRows == "") {
alert("Please enter rows!");
} else if (_tblCols == "") {
alert("Please enter columns!");
} else {
tblElm = document.createElement('table');
for (var i = 0; i < _tblRows; i++) {
rowElm = document.createElement('tr');
for (var j = 0; j < _tblCols; j++) {
let _randNmbr = Math.floor(Math.random() * 100) + 1;
randNmbrArray.push(_randNmbr);
colElm = document.createElement('td');
colElm.appendChild(document.createTextNode(_randNmbr));
rowElm.appendChild(colElm);
}
tblElm.appendChild(rowElm);
}
_tblDiv.innerHTML = "";
_tblDiv.append(tblElm);
_randNmbrAvg = GetAverage(randNmbrArray);
avgElm.innerHTML = "";
avgElm.append(`The average of the number in the table is ${_randNmbrAvg.toFixed(2)}`);
}
}
//Function to calculate average
function GetAverage(numberArray) {
let total = 0;
for (var i = 0; i < numberArray.length; i++) {
total += numberArray[i];
}
return total / numberArray.length;
}
/* CSS styling */
table {
border-collapse: collapse;
margin: auto 25px auto 25px;
}
table, td, th {
border: 1px solid #70AEC5;
}
td {
padding: 3px;
}
th {
border: 1px solid white;
background-color: #70AEC5;
color: white;
text-align: center;
padding: 4px 0 4px 0;
}
tr:hover {
background: #ddd
}
/* Additional styles */
.triangle {
background-color: #ffcccc; /* Light red color for highlighting */
}
<!-- HTML elements -->
<h1>Generating a Table</h1>
<h4>By Yukong Zhang</h4>
Rows: <input id="rows" type="text" size="3" value="15"> Columns: <input id="cols" type="text" size="3" value="15">
<button id="print" type="button" onclick="print_table()">Generate</button><br>
<div id="my_table"></div>
<h4 id="average"></h4>
My goal is to only highlight the lower half area of the table in a triangular shape.