JavaScript Programming/Conditions/Example Code
Appearance
example.html
[edit | edit source]<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-Control" content="no-cache">
<title>Example</title>
<style>
input {
width: 3em;
}
#error {
font-weight: bold;
}
</style>
<script defer src="example.js"></script>
</head>
<body>
<noscript>Enable JavaScript to see web page content.</noscript>
<p><input id="fahrenheit"></input>° Fahrenheit is <input id="celsius"></input>° Celsius</p>
<p><output id="error"></output></p>
</body>
</html>
example.js
[edit | edit source]// This program converts a Fahrenheit temperature to Celsius or
// a Celsius temperature to Fahrenheit.
//
// 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("fahrenheit").addEventListener("input", inputInput);
document.getElementById("celsius").addEventListener("input", inputInput);
});
function inputInput() {
let id = document.activeElement.id;
if (checkInput(id)) {
switch (id) {
case "fahrenheit":
fahrenheitInput();
break;
case "celsius":
celsiusInput();
break;
default:
console.log("Unexpected active element: " + id);
}
}
}
function checkInput(id) {
let value = document.getElementById(id).value;
if (isNaN(value) || value.trim().length == 0) {
document.getElementById("error").innerText = id + " must be a number!";
return false;
} else {
document.getElementById("error").innerText = "";
return true;
}
}
function fahrenheitInput() {
let fahrenheit = getFahrenheit();
let celsius = toCelsius(fahrenheit);
displayCelsius(celsius);
}
function getFahrenheit() {
let fahrenheit = document.getElementById("fahrenheit").value;
fahrenheit = Number(fahrenheit);
return fahrenheit;
}
function toCelsius(fahrenheit) {
let celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO;
return celsius;
}
function displayCelsius(celsius) {
celsius = celsius.toFixed(1);
document.getElementById("celsius").value = celsius;
}
function celsiusInput() {
let celsius = getCelsius();
let fahrenheit = toFahrenheit(celsius);
displayFahrenheit(fahrenheit);
}
function getCelsius() {
let celsius = document.getElementById("celsius").value;
celsius = Number(celsius);
return celsius;
}
function toFahrenheit(celsius) {
let fahrenheit = celsius / TEMPERATURE_RATIO + TEMPERATURE_DIFFERENCE;
return fahrenheit;
}
function displayFahrenheit(fahrenheit) {
fahrenheit = fahrenheit.toFixed(1);
document.getElementById("fahrenheit").value = fahrenheit;
}