Update, 5/14/2023: Version 3.2
Update, 5/11/2023: Version 3.1. Original: Version 2
I wrote a javascript calculator while I was waiting for something the other day. Here it is:
Permalink: Here
Technical Details
- Single, self-contained HTML file with embedded CSS and Javascript.
- The display width is configurable via a variable – currently 20 digits
- The top line is a “register” – normally this would be hidden on a desktop calculator. The two variables, “register” and “display” are global, which simplifies the architecture.
- The buttons are created using a function
- Binary math functions are performed by a wrapper that sanitizes the input values and then performs a callback to the underlying math operation – the pointer to the callback function is passed via onclick.
- Unary math functions are basically handled the same as binary operations, where onclick calls a wrapper, and the wrapper executes a callback.
To Do
(Updated, 5/11/2023)
Add MS, MR, M+, and M-, which will require a separate register.Add a configurable table of constants.Tool tips with enable/disable button.- Hex and binary functions, although these might be a separate calculator
Update: I think I will just make a dedicated programming calculator the next time I’m bored :-)
Funny Story about 3.1 vs 3.2
I uploaded version 3.1, and patted myself on the back for having done such a great job. Right-click, save as HTML, fire it up in Chrome, and…everything was rendering twice.
What happened??
The UI is dynamic, but the saved version of the page had BOTH a static copy of the dynamically-generated HTML, as well as the javascript code to dynamically generate the HTML. So every UI element was rendered TWICE. Worse, if you modify the Javascript at the top of the file to alter the constants or the display size, you would have one copy that’s correct because it’s dynamic, but the static copy would still be wrong.
Interestingly, if you View Source and save from there, it won’t have that problem, but that’s not what I was after.
To fix this, I changed from document.write to using extra SPANs for each block of UI elements, and setting innerHTML. Despite the fact that saving the file includes a static copy of the HTML, the dynamic code simply overwrites it each time the page is loaded. So if you change a Javascript variable and reload, the dynamic code blows away the static HTML and replaces it with a correct version.
Do you like it? Feel free to copy it. Click the permalink. Then right-click the calculator, and select “Save as html”.
Ideas or suggestions? Please feel free to leave me a comment.