// This program displays a temperature conversion chart and demonstrates
// JavaScript loops.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/JavaScript
"use strict";
const TEMPERATURE_DIFFERENCE = 32;
const TEMPERATURE_RATIO = 5 / 9;
window.addEventListener("load", function () {
document.getElementById("start").addEventListener("focus", inputFocus);
document.getElementById("stop").addEventListener("focus", inputFocus);
document.getElementById("step").addEventListener("focus", inputFocus);
document.getElementById("start").addEventListener("input", inputInput);
document.getElementById("stop").addEventListener("input", inputInput);
document.getElementById("step").addEventListener("input", inputInput);
document.getElementById("start").focus();
});
function inputFocus() {
document.activeElement.select();
document.getElementById("error").innerText =
"Enter " + document.activeElement.id + " value.";
}
function inputInput() {
let value = document.activeElement.value;
if (checkInput()) {
document.getElementById("error").innerText = "";
displayTable();
}
}
function checkInput() {
let value = document.activeElement.value;
if (isNaN(value) || value.trim().length == 0) {
document.getElementById("error").innerText =
document.activeElement.id + " must be a number!";
return false;
}
value = document.getElementById("start").value;
if (isNaN(value) || value.trim().length == 0) {
return false;
}
value = document.getElementById("stop").value;
if (isNaN(value) || value.trim().length == 0) {
return false;
}
value = document.getElementById("step").value;
if (isNaN(value) || value.trim().length == 0) {
return false;
}
return true;
}
function displayTable() {
let start = Number(document.getElementById("start").value);
let stop = Number(document.getElementById("stop").value);
let step = Number(document.getElementById("step").value);
if (stop < start) {
document.getElementById("error").innerText = "Stop must be greater than or equal to start!"
document.getElementById("tbody").innerText = "";
return;
}
if (step <= 0) {
document.getElementById("error").innerText = "Step must be greater than or equal to 0!"
document.getElementById("tbody").innerText = "";
return;
}
let result = ""
for (let fahrenheit = start; fahrenheit <= stop; fahrenheit += step) {
let celsius = fahrenheitToCelsius(fahrenheit);
celsius = celsius.toFixed(1);
result += `<tr><td>${fahrenheit}</td><td>${celsius}</td></tr>`;
}
document.getElementById("tbody").innerHTML = result;
}
function fahrenheitToCelsius(fahrenheit) {
let celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO;
return celsius;
}