How to make a bookmarklet for temperature conversion

A bookmarklet is a tiny JavaScript program stored as a bookmark. In principle, to start the program you could type the whole script text into the browser's address field each time, like a URL, and press Enter. But for convenience, like with URLs, we will create a bookmark from the script text.
[This example is for Firefox.*) You should have the Bookmarks toolbar visible (menu: View>>Toolbars).]
*) Bookmarklets stopped working with Firefox versions above 4; but as of 2020, after a small modification, it seems to be working fine again.

Here is what you have to do to create a bookmarklet

... in this case, a conversion tool for temperature scales (Celsius/Fahrenheit):

  1. Right-click on bookmarks toolbar, select "New Bookmark..."
  2. Enter a name, eg. °F<->°C
  3. In the "Location" field, paste the following script text (there can be no line breaks in the field; make sure you got the whole text!):
    javascript:s=document.getSelection();if(s==''){void(s=prompt('Input temperature value (no units):',''))};if(s && isNaN(Number(s)))alert('Input or highlight a number please.');else if(s)alert('(°F - 32) / 1.8 = °C\n'+s+' °F = '+Math.round((s-32)/.18)/10+' °C\n\n1.8 ×°C + 32 = °F\n'+s+' °C = '+Math.round(18*s+320)/10+' °F')
  4. Click the "Add" button to save the bookmarklet. (All other fields can be left blank.)

How to use it

There are two ways to use your bookmarklet: Input mode, and Capture mode.

Note 1: Input or highlight numbers only, no temperature units (or other text). Your conversion tool works in both directions at the same time, so you don't have to specify what temperature scale your input is. Just select the matching answer from the output.
Note 2: The conversion formula for each direction is given along with the respective output value.


How it works  (Tech stuff)

This is pretty much straightforward:


Created: Nov 28, 2009 / Updated: Dec 9, 2020
by Daniel Palloks