Emphasize the cells located in the bottom left quadrant of the table (triangular shape)

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.

Answer №1

In essence, the comparison between the x and y coordinates of a cell is crucial. In a square matrix, different conditions apply to various sections: the lower left triangle satisfies x <= y, the top left matches y <= numberOfColumns - x, and so on...

To highlight the lower left cells, just assign the triangle class to every cell that meets the condition j <= i (i represents the current row index and j represents the current column index).

Given that the generated matrix may not always be a square one (with varying number of columns and rows), we must normalize the x and y coordinates. This normalization involves dividing the x coordinate by the number of columns and the y coordinate by the number of rows, ensuring both normalized coordinates range from 0 to

1</code). Consequently, we emphasize the cells satisfying <code>j / (_tblCols - 1) <= i / (_tblRows - 1)
(subtracting 1 from both rows and columns to accommodate the fact that indexes start at 0).

Add the following within the inner loop:

if(j / (_tblCols - 1) <= i / (_tblRows - 1)) {
    colElm.className = "triangle";
}

Demonstration:

(previously shared code snippet)

Answer №2

My approach involves calculating the slope of a line that cuts the chart in half and then updating the count of colored cells based on this slope.

var slope = _tblCols/_tblRows

Demo:

//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');
        var coloredCells = 1
        var slope = _tblCols/_tblRows //Calculate the slope
        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');
              if(j < coloredCells){
                colElm.classList.add("triangle")
              }
                colElm.appendChild(document.createTextNode(_randNmbr));
                rowElm.appendChild(colElm);

            }
            coloredCells+= slope; //Increment by the slope
            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 GetAverage(numberArray){
let total = 0;
for(var i = 0; i < numberArray.length; i++) {
    total += numberArray[i];
}
return total / numberArray.length;
}
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}

h1{
    color: #70AEC5;
}

#directions {
    border-radius: 25px;
    border: 2px solid #70AEC5;
    padding: 10px; 
    margin: 10px 25px 15px 25px;
}

button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 20px;
    cursor: pointer;
    border-radius: 8px;
}

.triangle
{
   background-color:#ffcccc;
}
<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ember 2: Display a loading message only if the IDs were part of the initial response

I frequently use the following code snippet in my projects: {{#each model.posts as |post|}} <div>post.title</div> {{else}} <div>Loading the posts...</div> {{/each}} However, I sometimes face uncertainty regarding whether t ...

Choose the singular Element lacking both a class or an ID

I came across this and that question, however, they are both focused on Javascript. I am searching for a way to target the lone div that does not have an ID or Class assigned to it. For instance: <body> <div class="X" ... /> <div class="Z ...

How can I change an array to a string in JavaScript/jQuery and add a specific

Currently, I am tasked with the challenge of converting an array into objects. Furthermore, I also need to add something before each object is displayed. var arrayList = ["image1.jpg","image2.jpg","image3.jpg"]; The desired outcome should look like this ...

Is it possible to change the text displayed when hovering over various images using just CSS and HTML?

I have created an image and text hover effect. There are four images and corresponding paragraphs for each image. When hovering over an image, the specific paragraph should replace the previous one using only HTML and CSS. Please note the following: The de ...

The Struts2 jsp page is popping up in a separate window instead of loading within the content div

In my Struts2 application, the home page layout consists of a Header, Menu, Content, and Footer sections arranged horizontally. When a menu item is clicked, a "navigate" action is triggered using JQuery and Ajax. The menu name is passed as a parameter to t ...

What is the best way to access the child component in React?

const navArr = [ { path: "/introduction", title: "회사소개", subTitle: [{ title: "summary" }, { title: "vision" }], }, ] {navArr.map((obj) => { return ( <NavItem> ...

CSS code for targeting specific screen sizes in the Bootstrap grid system

I'm not an expert in styling, but I often use Bootstrap for small projects. Currently, my main challenge lies within the grid system. With one monitor at a 1920x1080 resolution and another at 1366x768, I find myself wanting to adjust the grid system b ...

Creating a multi-dimensional array in order to store multiple sets of data

To generate a multidimensional array similar to the example below: var serviceCoors = [ [50, 40], [50, 50], [50, 60], ]; We have elements with latitude and longitude data: <div data-latitude="10" data-longitude="20" clas ...

Tips on concealing the overflow content within a Material UI table cell, rather than allowing it to wrap around

I have been trying to use the material UI Table component in order to display a table. The issue I am facing is that when the content in a cell exceeds the allotted space, instead of showing ellipses (...), the text wraps within the cell. I attempted to ap ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Connect various models together, or create synchronized computed properties

At times, the model abstraction may fall short, leading to the necessity of synchronizing two different models. For instance, I have two lists linked by an angular sortable, which requires a model structure like this: left = [{name:"one"}, {name:"two"}]; ...

Display a loading state in Next.js until the page has finished loading completely

When working with a page that includes both getStaticProps and getStaticPaths, you may have noticed that loading the page can take some time, leaving the front-end blank. To enhance the user experience, you might want to display a simple message such as "P ...

Is there a way to create a layout with three columns of divs, where the middle column is shifted, that automatically collapses into two columns with the second one shifted when the window size is reduced?

For the about page of my website, I have a grid layout consisting of three columns. The challenge is to offset the center column by 50%. When the window size is reduced beyond a certain point, I want the third column to disappear and its images to be distr ...

Ways to enhance the performance of my websites' backend systems

Greetings! I am currently working on developing backends in ASP.NET 2.0, and have taken steps to optimize the performance by caching images, GZIPing CSS and JS files. The load speed of each option is good, but I am eager for even faster loading times. Alt ...

Is there a way to prevent onclick events from executing when the page is refreshed?

I have a JSF project and I am using the menuitem to navigate between pages. I added an ONCLICK event to the menuitem because I need to perform an action before redirecting the user to the desired page. The issue arises when the page containing the ONCLIC ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...

What is causing the height:auto property to not function on these two elements?

I am facing an issue where the main-div and footer-div are not growing with the content as expected. While setting the height to auto works fine for the footer, it messes up the page for the main content. Specifically, the footer ends up taking over the en ...

Automatically trigger a Bootstrap 5.2 modal when the page loads

Currently, I've been utilizing Bootstrap in conjunction with JQuery and have a specific code snippet that displays a Modal when a page is loaded. However, with the latest version 5.2 of Bootstrap, there is a push to move away from using JQuery (which ...

Error: Unable to run 'play' on 'HTMLMediaElement': Invocation not allowed

Just a simple inquiry. I am trying to store an HTMLMediaElement method in a variable. // html segment <video id="player" ... /> // javascript segment const video = document.querySelector('#player') const play = video.play video.play() / ...

Add the Bootstrap CSS to the <head> section using Wicket

Currently, I am utilizing Wicket to generate the HTML content of an email. Although I prefer using Bootstrap for styling, I encounter issues since link tags are disregarded in emails... I am wondering if there is a convenient method in Wicket to import the ...