Creating a Temperature Converter without a single line of JS
Rajasegar Chandran
Posted on March 5, 2021
This is the second in the series of posts about using hyperscript a scripting language designed for the web, inspired by HyperTalk, for building components in HTML. If you want to take a look at the first introductory post, you can check it here.
Creating a Counter component without a single line of JS
Rajasegar Chandran ・ Mar 4 '21
In this post, we are going to build a Temperature Converter component which converts Celcius values to Fahrenheit and vice versa. This component is inspired from the 7GUIs project where we build simple user interfaces in various languages and frameworks to benchmark the complexity and code involved.
So let's just get into the HTML code first and will see what each line of code is doing.
The code
<script src="https://unpkg.com/hyperscript.org@0.0.4"></script>
<p>
<input id="txtCel" type="number" _="on change set #txtFah.value to ( 32 + (me.value * (9/5))).toFixed(1) " value="0"> Celcius =
<input id="txtFah" type="number" _="on change set #txtCel.value to ((5/9) * (me.value - 32)).toFixed(1)" value="32"> Fahrenheit
</p>
As I promised in my first post, all the code examples are terse, having just a few lines to implement simple UI components.
Our first line of code is to import the hyperscript
library from the unpkg CDN. The we are creating two input elements with type as number
, one for the Celcius values and the other for Fahrenheit.
And then we define the onChange
event of each these inputs to update the Celcius and Fahrenheit values deriving from one another based on a simple formula. So when you update the Celcius values, the Fahrenheit values are automatically calculated based on it.
<input id="txtCel" type="number" _="on change set #txtFah.value to ( 32 + (me.value * (9/5))).toFixed(1) " value="0">
The script above says
On the 'change' event for this input, set the value of the element with id `txtFah` to the calculated value based on the current element's (me) value and round it off to one decimal point
The on
feature allows you to embed event handlers directly in HTML and respond to events with hyperscript:
<button _="on click add .clicked">
Add The "clicked" Class To Me
</button>
The underscore (_) attribute is where the hyperscript runtime looks for hyperscript on an element by default.
We can access the current element in the event handler using the built-in me
object using hyperscript and the other input element using its element identifier. The assignments can be performed using the set
command in hyperscript and finally we are rounding off the values to one decimal place using the toFixed
function in Javascript.
You can take a look at the component in action in this Codepen.
Posted on March 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.