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 don't have to.

Add two columns to the table: Start lbs and Now lbs, plus an empty Gain column. Put the numbers on the row as data-start and data-current.

Live result

Step 1 โ€” mark the rows


  Black Gold
  FW-01
  Texas Longhorn
  1100
  1280
  โ€”

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

Step 2 โ€” script.js

New file in the same folder. Link it at the bottom of body:

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";
  });
});

Click the button. Gain should fill in. That's the page doing ranch math.

โ† Lesson 2 All lessons Lesson 4 โ€” JSON โ†’