Lesson 3 โ€” Let the Page Do the Math

JavaScript ยท done when weight gain calculates on click

HTML is bones. CSS is paint. JavaScript is the hired hand that does the arithmetic so you do not sit there with a pencil every time a steer comes off the scale.

We are going to add starting weight and current weight to the card, then a button that fills in the gain. You already know the four names. Now the page does the subtraction.

Here is the finished look

Click Calculate gain in the preview. The last column should fill in.

Step 1 โ€” put the numbers on the row

Add columns for Start, Now, and Gain. Hang the numbers on the row itself as data-start and data-current so the script can find them later. One animal looks like this:

<tr data-start="1100" data-current="1280">
  <td>Black Gold</td>
  <td>FW-01</td>
  <td>Texas Longhorn</td>
  <td>1100</td>
  <td>1280</td>
  <td class="gain">โ€”</td>
</tr>

Do that for all four. Then put a button under the table:

<p><button id="calc-btn" type="button">Calculate gain</button></p>

Step 2 โ€” a second file for the math

Create script.js in the same folder. At the bottom of the HTML body, load it:

<script src="script.js"></script>

Inside script.js, listen for a click, walk every marked row, subtract, and write the answer into the Gain cell.

document.getElementById("calc-btn").addEventListener("click", function () {
  document.querySelectorAll("tr[data-start]").forEach(function (row) {
    var start = Number(row.getAttribute("data-start"));
    var current = Number(row.getAttribute("data-current"));
    row.querySelector(".gain").textContent = (current - start) + " lbs";
  });
});

Save, refresh, click the button. If Black Gold shows 180 lbs, the hired hand showed up for work.

Next lesson we stop typing animals into HTML and write them as a list of data instead.

โ† Lesson 2 All lessons Lesson 4 โ†’