WP5000

WordPress Tips, Tricks and Techniques

How To Build a Converter

Prerequisite: How to Embed Javascript

In the following example, we’ll build a Fahrenheit – Celsius converter. This uses standard Gutenberg HTML blocks. If you prefer the classic editor, the coding is the same, and will work fine when built in the [Text] tab.

Notice that the first two elements above are also HTML blocks which are used to create the divs on which the javascript will operate.

Here it is in operation:

Fahrenheit:
Celsius:

And here is the code. First, we create two input fields in which the user can enter either Fahrenheit or Celsius. In this Gutenberg block version, they are both HTML blocks inside a Column block with two columns. In a classic editor, or in plain HTML, you can place each div in an encompassing div, or table cells. These are surrounded by div elements for for a slightly nicer appearance.

Fahrenheit:
<br><div style="background-color:#def; padding:8px;"><center>
<input type="text" id="FahrenheitBox" oninput="goFigure(this)">
</center></div>
Celsius:
<br><div style="background-color:#def; padding:8px;"><center>
<input type="text" id="CelsiusBox" oninput="goFigure(this)">
</center></div>

Note that we use oninput() rather than onchange(). Javascript is a bit unusual in that onchange() will only react once when the page is displayed.

The oninput calls the goFigure() function, and passes ‘this’ which is a reference to the input element itself.

Here’s the HTML block containing the javascript:

<script>
function goFigure(e){
   if (e.id == 'FahrenheitBox'){
      let fahrenheit = document.getElementById('FahrenheitBox').value;
      let celsius = (fahrenheit - 32) * 5 / 9;      
      document.getElementById('CelsiusBox').value = celsius;
   } else {
      let celsius = document.getElementById('CelsiusBox').value; 
      let fahrenheit = (celsius * 9 / 5) + 32;
      document.getElementById('FahrenheitBox').value = fahrenheit;
   }
} // end of gofigure() 
</script>

The first thing goFigure() does is get the element Id that was passed through the parameter e so we know whether to convert from or to Celsius.

We do the math in both cases, then send our new number back to the appropriate input element’s value parameter.

Of course you could use any calculation with as many steps as you’d like, such as cubic feet to cubic meters, mortgages, drops to liters, or apples to oranges, if you know how to quantify apples and oranges.


Leave a Reply

Your email address will not be published. Required fields are marked *

There is no need to be confused, frustrated, or waste time with WordPress issues. I’ll be glad to help with phone or screen sharing. I charge $2/minute, with no minimum. The typical call runs 9 minutes ($18). If I can’t efficiently solve your problem, there’s no charge for the call. Contact me any time at (805)-843-5353. You’ll enjoy my friendly, informative manner! – Jeff


Categories