Kilometer/mile converter redux, jQuery version

Sunday, 14 October 2007

I wrote a nice little JavaScript kilometer/mile converter awhile back. I tried to be pretty explicit in the code to do everything step by step and all in JS. 31 lines of code. Not too bad for a calculator and shorter than if we didn’t use ternary logic.

I have been using jQuery a little for quite awhile now. I wish I had time to use it more. Every single time I revisit it I learn something new and see it is even better than I remembered. I rewrote the converter with it as an experiment. 9 or 10 lines of JS now.

The new code

<script id="kilo_mile" type="text/javascript">//<![CDATA[
// Remember! The jQuery lib must be loaded already for this to run.
$('<form><fieldset><legend>kilometer/mile converter</legend>' +
  '<input id="kilo" type="text"/>' +
  '<input id="mile" type="text"/>' +
$("#kilo, #mile").keyup(function(evt) {
         var update = == "mile" ? "#kilo" : "#mile";
     var conversion = == "mile" ? 1.609 : 0.6214;
            var val = new Number( $( * conversion );
        $(update).val( isNaN(val) ? "Numbers only!" : val );

The demo

2 comments · Commenting is closed
digg stumbleupon reddit Fark Technorati Faves




Re: Kilometer/mile converter redux, jQuery version

Have you ever played around with Flapjax? I haven't tried it yet, but if you have, I'd be curious to see your take on it...

By Jen on 14 October 2007 · 09:17

A is A

Re^2: Kilometer/mile converter redux, jQuery version

I didn’t know anything about it till now. It is very interesting and I can imagine wanting to use it for an embedded application or something but until I had a case like that where I wanted to wrap stuff up in a single app instead of relying on another app (like Firefox or IE) to run code I probably wouldn’t mess with it. So much to learn and so little time already.

I’m more interested in chrome stuff on Firefox right now; and someone turned me on to Erlang recently which I’m also curious about working with. I’m considering doing some sort of plugin with chrome/FF (a real one, I have a couple stupid demos/tests). But, again, so much to learn/do, so little time.

By A is A on 14 October 2007 · 13:50