Posts Tagged ‘JavaScript’

webLightSwitch Project Announcement

Wednesday, January 25th, 2012
Screen shot of webLightSwitch running in the Android browser

Screen shot of webLightSwitch running in the Android browser

I have developed a new project called webLightSwitch. You can find details about the project on the webLightSwitch project page. The project is a simple but useful program to allow me to control some of the lights in my home via a web interface. This allows me to use my mobile phone to turn on and off the lamp or the outdoor lights at my house. The control software is written in JavaScript and runs on a BeagleBone using node.js. The user interface, as seen in the screen shot, is implemented with jQuery Mobile to make the interface touch friendly. The lights are controlled by Smarthome INSTEON controllers. The BeagleBone communicates with the lighting controllers via a Smarthome PowerLinc Modem.

I have been running the software for over a week now. With it being winter right now in Iowa, it gets dark well before I arrive home from work around 6PM. Using my mobile phone to be able to turn on the outdoor lights is very convenient. The experience is similar to my automatic garage door opener: drive up to drive way, press button to open garage door, and press button to turn on outside lights.

I plan to develop a more advanced home automation system, but this simple system has proven itself to be useful. In addition to the webLightSwitch project page, you can find the source code on GitHub and a video demonstration on YouTube.

lightningtimer.net

Thursday, November 13th, 2008

I found Simon Willison’s lightningtimer.net Javascript timer to be totally awesome. The app is written in Javascript, all on one page. It lets you specify a time, and then a big-font timer counts down. The timer takes up the whole page. It can give you a warning, the background turns pink, when the timer is almost up. When the timer reaches zero, the background turns red and 0:00 blinks. Take a look at the page source for documentation on how to use lightningtimer.net. He says that he needed something for a Lightning Talk and this is the result.

Looking at the code (like I said, the Javascript is all in the page source, so just “view source” in your browser), it is a really cool example of Javascript. I was amazed how simple and elegant Simon’s code was. As someone who definitely is a poor Javascript hack, it is nice to see some good Javascript. And, I can use it as a tea timer too! 🙂

Greasemonkey for Pearson Access

Wednesday, November 12th, 2008

During the day, I professionally work on a web application called Pearson Access. Today we determined that we needed a user administration process for one of our Pearson Access customers that would require them to always select a certain user role when creating a new user. The system doesn’t auto-check the role, the user will need to be trained to check it.

But, being a geek, that got me thinking. What if Greasemonkey could be used with a Greasemonkey script in Firefox to automatically check a role when creating a new user account. So, I wrote such a script: autoselectrole.user.js.

“Built in” text field calculator

Wednesday, September 26th, 2007

I have a little web application that I wrote to balance my check book. I often enter a calculated value into a form text field. I usually use the Google Calculator in the Firefox Search Bar to perform the calculations. I often perform simple calculations like “25 * .03”. (Why? I impose a personal finance fee on each credit card purchase that I make. I use a 3% fee. I put all of my personal finance fees into an online high-interest savings account. So, if I charge $25.00 on a card, I transfer “25 * .03” or $0.75 to my online savings account. It isn’t much, but it adds up.) So, yesterday, I thought, “I wonder if I can integrate Google Calculator functionality into my web application?”

Here is what I came up with.

Calculator example.

You can take a look at the source of the “calculator.html“. It includes “JPetersonCalculator100.js“, which is where the JavaScript that actually implements the calculator is sourced. The calculator function is attached to the text input field using an onKeyPress event handler in the HTML:

onkeypress="processCalculatorKeyPress(event, 2);"

Here is the processCalculatorKeyPress function.

001: /**
002:  * Handle a key press from a text field that can automatically calculate a
003:  * derived value. Basically, enter normal mathematical formula like
004:  * "5 * .03 =". When you press the equal ("=") key, the value in the text field
005:  * will be replaced with the calculated value. If the value can't be
006:  * calculated, it is left unchanged.
007:  *
008:  * @param e the event
009:  * @param precision the decimal precision to round to.
010:  */
011:  function processCalculatorKeyPress(e, precision) {
012:   var targ;
013:   if (!e) var e = window.event;
014:   if (e.target) targ = e.target;
015:   else if (e.srcElement) targ = e.srcElement;
016:   if (targ.nodeType == 3) // defeat Safari bug
017: 	targ = targ.parentNode;
018:
019:   if (e.keyCode) code = e.keyCode;
020:   else if (e.which) code = e.which;
021:
022:   if (code == 61) { // '='
023:     var expression;
024:     var result;
025:     expression = targ.value;
026:
027:     try {
028:       // calculate, evaluating arithmetic expression
029:       result = eval(expression);
030:
031:       if (typeof result == "number") {
032:         // round, if necessary
033:         if (typeof precision == "number") {
034:           if (precision > 0) {
035:             if (result.toFixed) {
036:               result = result.toFixed(precision);
037:             } else {
038:               var factor = Math.pow(10,precision);
039:               result = Math.round(result * factor) / factor;
040:             }
041:           }
042:         }
043:
044:         targ.value = result;
045:
046:         // don't display key that triggered the calculation
047:         if (e.preventDefault) {
048:           e.preventDefault();
049:         } else {
050:           e.returnValue = false; // IE
051:         }
052:       }
053:     } catch (e) {
054:       // expression wasn't an arithmetic expression, let normal text be displayed
055:     }
056:   }
057:
058:   // var character = String.fromCharCode(code);
059:   // alert('Code was: ' + code + ' Character was: [' + character + '] targ: [' + targ.value + ']');
060:
061:   return false;
062: }

Lines 12 -10 process the event, makeing a “normalized” version that handles differences in browser implementations. Since the function processCalculatorKeyPress is called for EVERY key press, line 22 filters out all key presses except for the one that we care about: the equals (“=”) key. Line 25 saves the value currently entered into the text field. Line 29 uses the JavaScript eval function to evaluate the arithmetic expression. (This is the actual calculator. The rest of the function make the results look pretty.) The “try”, on line 27, and associated “catch”, on line 53, are there to handle any error thrown by the “eval” function. An error would be thrown if the value entered into the test field was not an arithmetic expression. (Or more generally, not a valid JavaScript expression, since “eval” found evaluate any valid JavaScript expression. But that’s not really useful for the calculator.) Line 31 makes sure that the result of the “eval” is a number. Note that execution will only reach line 31 if “eval” didn’t throw an exception. Lines 33 through 41 perform any required rounding of the result. If available, line 36 uses the “toFixed” function to convert the number to the requested number of decimal places, rounding and padding with zero as necessary. If this function is not available, lines 38 and 39 perform rounding without any padding. Line 44 assigns the result of the arithmetic expression to the text input form element. Lines 47-51 indicate that the calculation succeeded so that the equals sign isn’t added to value of the text input field. Line 58 and 59 are commented out. But they illustrate how you can use an alert box to see what characters are pressed. I used this technique when developing the function.

That’s it. It should be relatively easy for you to include this build in text field calculator into your own web application. The basic steps are:

  1. Include the JavaScript function “processCalculatorKeyPress”.
  2. Add the “onkeypress” to the text fields that you would to support the build in calculator functionality. You can configure the precision value, from no rounding (use a negative value, like “-1”) to whatever decimal place is important. For currency input, I use a precision of “2”.