JavaScript utility: kilometer/mile converter

The page Stupid Perl tricks: kilometer/mile converter is actually getting found quite a bit via Google and such. The problem for most seekers is that they have no interest in a big, somewhat obfuscated Perl substitution routine. They are looking for a real converter, or one for their own site.

So here it is. A real live converter in JavaScript which you are welcome to use for your own site; CC 3.0 Attribution.

By the way, all you really need is a calculator or a decent head for math. One mile is 1.61-ish kilometers and one kilometer is 0.62-ish miles. An easy breakpoint to remember for rough comparisons in your head is 55mph is 88kph.


JavaScript error.

The code

<div id="sedition_km">
JavaScript error.
<noscript>Enable JavaScript in your browser
to use this utility.</noscript>
<script type="text/javascript">//<![CDATA[
// (c) Ashley Pond V; CC Attribution 3.0 Unported; retain this notice
 var me = new Object ({});
 me.km2ml = new Number(1.609);
 me.ml2km = new Number(0.6214); = document.getElementById("sedition_km");;
 me.form = document.createElement("form");;
 me.f1 = document.createElement("fieldset");
 me.legend1 = document.createElement("legend");
 me.legend1.appendChild( document.createTextNode("Kilometer/Mile converter") );
 me.kilo = document.createElement("input");
 me.kilo.setAttribute("name", "kilometer");
 me.kilo.setAttribute("size", "21");
 me.kilo.onkeyup = convert;
 me.mile = document.createElement("input");
 me.mile.setAttribute("name", "mile");
 me.mile.setAttribute("size", "21");
 me.mile.onkeyup = convert;
 function convert (evt) {
   if (!evt) evt = window.event;
   target = || evt.srcElement || evt.parentNode;
   var update = == "mile" ? me.kilo : me.mile;
   var conversion = == "mile" ? me.km2ml : me.ml2km;
   var val = new Number( target.value * conversion );
   update.value = isNaN(val) ? "Numbers only!" : val;
//]]> </script>

You can see it is a bit verbose. We have no form or input fields in the placeholder div tag we will use to put our markup. Why use JavaScript to write all the HTML? Because this means it will work and write the proper level of HTML—e.g., XHTML 1.0 or HTML 4—no matter where it is run. It also makes it a bit easier to just drop in someplace else.

Update: Kilometer/mile converter redux, jQuery version

digg stumbleupon reddit Fark Technorati Faves