Multiplication Chart: Code Your Own Times Table Using JavaScript

Multiplication is one of the essential building blocks of mathematics. Memorizing the times tables up to 10×10 or 12×12 lays an important foundation for working with numbers throughout school and life. A multiplication chart provides a helpful visual reference and practice tool for learning this critical skill.

In this article, we‘ll walk through how to code your own interactive multiplication table using HTML, CSS, and JavaScript. Even if you‘re new to web development, you‘ll be able to follow along and create a functional multiplication chart by the end. Let‘s get started!

Setting Up the HTML Structure

The first step is to set up the basic structure of our multiplication table in HTML. We‘ll use a <table> element to arrange the numbers in a grid format.

<table id="multiplicationTable">
  <tr>
    <th>×</th>
    <th>1</th>
    <th>2</th>
    <th>3</th>
    ...
    <th>10</th>
  </tr>
  <tr>
    <th>1</th>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    ...
    <td>10</td>
  </tr>
  <tr>
    <th>2</th>
    <td>2</td>
    <td>4</td>
    <td>6</td>
    ...
    <td>20</td>
  </tr>
  ...
  <tr>
    <th>10</th>
    <td>10</td>
    <td>20</td>
    <td>30</td>
    ...
    <td>100</td>
  </tr>
</table>

Here we‘ve hardcoded the values, but later on we‘ll see how to generate the table dynamically with JavaScript.

The <th> elements represent the header cells, which label each row and column. The <td> elements are the standard cells that contain the products.

Styling with CSS

Next, we‘ll add some CSS to make our multiplication table more visually appealing. Feel free to customize the colors and fonts to your liking.

table {
  border-collapse: collapse;
  margin: 20px auto;
}

th, td {
  border: 1px solid black;
  padding: 5px;
  text-align: center;
  width: 50px;
  height: 50px;
}

th {
  background-color: #ddd;
  font-weight: bold;
}

td:hover {
  background-color: #ffd333;
  cursor: pointer;
}

This CSS collapses the border between cells, centers the text, sets a fixed size for each cell, and adds a hover effect to the products. The table is also centered on the page with auto margins.

Generating the Table with JavaScript

Hardcoding the multiplication table works fine for a 10×10 grid, but what if we wanted a 12×12 or 20×20 table? Instead of manually typing out all those cells, we can use JavaScript to generate the table dynamically.

const multiplicationTable = document.getElementById(‘multiplicationTable‘);

function generateTable(rows, cols) {
  const thead = multiplicationTable.createTHead();
  let row = thead.insertRow();
  let th = document.createElement(‘th‘);
  th.innerHTML = ‘ב;
  row.appendChild(th);

  for (let i = 1; i <= cols; i++) {
    th = document.createElement(‘th‘);
    th.innerText = i;
    row.appendChild(th);
  }

  for (let i = 1; i <= rows; i++) {
    row = multiplicationTable.insertRow();
    th = document.createElement(‘th‘);
    th.innerHTML = i;
    row.appendChild(th);

    for (let j = 1; j <= cols; j++) {
      let cell = row.insertCell();
      cell.innerText = i * j;
    }
  }
}

generateTable(10, 10);

Let‘s break this down:

  1. We grab a reference to the table element using its ID.
  2. We define a function called generateTable that accepts the number of rows and columns as parameters.
  3. We create the <thead> section and insert the header row with the multiplication symbol in the corner.
  4. We loop through the number of columns, inserting <th> elements with the column numbers.
  5. We loop through the number of rows, inserting a new table row (<tr>) for each one.
  6. For each row, we insert a <th> with the row number, then loop through the columns, calculating the product and inserting it into a <td> cell.
  7. Finally, we call the generateTable function, passing in 10 for both the rows and columns.

Now if you want to change the size of the multiplication table, you only need to adjust the arguments passed to the generateTable function.

Adding Interactivity

To make our multiplication chart even more engaging, let‘s add some interactive features using JavaScript. Here are a few ideas:

Announce Products on Hover

When the user hovers over a table cell, we can use the Web Speech API to announce the product. This provides an auditory reinforcement and makes the chart more accessible.

const synth = window.speechSynthesis;

function announceProduct(event) {
  const cell = event.target;
  const product = cell.innerText;
  const utterance = new SpeechSynthesisUtterance(product);
  synth.speak(utterance);
}

multiplicationTable.addEventListener(‘mouseover‘, announceProduct);

Highlight Rows and Columns

To help users track across rows and columns, we can highlight the current row and column when hovering over a cell.

const cells = document.querySelectorAll(‘td‘);

cells.forEach(cell => {
  cell.addEventListener(‘mouseover‘, event => {
    const row = event.target.parentElement;
    const col = event.target.cellIndex;

    row.classList.add(‘highlight‘);
    cells.forEach(cell => {
      if (cell.cellIndex === col) {
        cell.classList.add(‘highlight‘);
      }
    });
  });

  cell.addEventListener(‘mouseout‘, event => {
    const row = event.target.parentElement;
    const col = event.target.cellIndex;

    row.classList.remove(‘highlight‘);
    cells.forEach(cell => {
      if (cell.cellIndex === col) {
        cell.classList.remove(‘highlight‘);
      }
    });
  });
});
.highlight {
  background-color: yellow;
}

Display Multiplication Formula

When clicking on a cell, we can display the full multiplication formula (e.g. "3 × 7 = 21") below the table.

<p id="formula"></p>
const formula = document.getElementById(‘formula‘);

function displayFormula(event) {
  const cell = event.target;
  const row = cell.parentElement.rowIndex;
  const col = cell.cellIndex;
  const product = cell.innerText;

  formula.textContent = `${row} × ${col} = ${product}`;
}

multiplicationTable.addEventListener(‘click‘, displayFormula);

Taking It Further

There are many more possibilities for extending and customizing your multiplication chart. Here are a few ideas to explore:

  • Allow the user to input their own range for the rows and columns.
  • Add a quiz mode that prompts the user to fill in random products.
  • Animate the cells when the correct product is hovered or clicked.
  • Use CSS Grid or Flexbox for more flexible layouts.
  • Make the table responsive for different screen sizes.

You can find more inspiration and resources for learning JavaScript and building interactive web projects on sites like freeCodeCamp, MDN Web Docs, and CSS-Tricks.

Conclusion

Congratulations, you now have a fully functional, interactive multiplication chart! By coding this project, you‘ve practiced working with HTML tables, CSS styling, JavaScript DOM manipulation, and more.

Building projects like this is a great way to reinforce your coding skills and learn new web development techniques. Keep experimenting and adding your own creative twists. Happy coding!

Similar Posts