JavaScript Programming/Events/Example Code

example.html

edit
<!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;
    }
  </style>
  <script defer src="example.js"></script>
</head>

<body>
  <noscript>Enable JavaScript to see web page content.</noscript>

  <p><input id="fahrenheit">° Fahrenheit is <output id="celsius"></output>° Celsius</p>
</body>

</html>

example.js

edit
// This program converts a Fahrenheit temperature to Celsius.
//
// 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", fahrenheitInput);
});

function fahrenheitInput() {
  let fahrenheit = getFahrenheit();
  let celsius = fahrenheitToCelsius(fahrenheit);
  displayResults(fahrenheit, celsius);
}

function getFahrenheit() {
  let fahrenheit = document.getElementById("fahrenheit").value;
  fahrenheit = Number(fahrenheit);
  return fahrenheit;
}

function fahrenheitToCelsius(fahrenheit) {
  let celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO;
  return celsius;
}

function displayResults(fahrenheit, celsius) {
  celsius = celsius.toFixed(1);
  document.getElementById("celsius").innerText = celsius;
}