Calculators & Utilities

Free Unit Converter Widget

Let visitors convert length, weight, temperature, and volume on your site.

A clean unit converter your visitors can use to switch between length, weight, temperature, and volume units, with all conversion math built in — no API calls or external services. It updates live as they type, and includes a swap button for flipping from and to units. Install it with a single script tag — no dependencies, no accounts.

Live demo

Embed this widget

Paste either snippet into your page — a Custom HTML block on WordPress, Shopify, or Squarespace works too. Both snippets update live as you customize, so what you copy is exactly what you configured.

Hosted (recommended)html
<script src="https://hayneslab.dev/widgets/unit-converter.js" async></script>
<!-- Free Unit Converter widget by haynes lab — https://hayneslab.dev/tools/widgets/unit-converter -->
Inline (self-contained)html
<!-- Free Unit Converter widget by haynes lab — https://hayneslab.dev/tools/widgets/unit-converter -->
<script>
/*!
 * haynes lab — Unit Converter widget (free)
 * Docs & embed code: https://hayneslab.dev/tools/widgets/unit-converter
 */
(function () {
  'use strict';

  var PREFIX = 'hlw-unit-converter';
  var STYLE_ID = 'hlw-unit-converter-styles';

  // Linear categories convert through a base unit; temperature is special-cased.
  var CATEGORIES = {
    length: {
      label: 'Length',
      units: {
        mm: { label: 'Millimeters (mm)', factor: 0.001 },
        cm: { label: 'Centimeters (cm)', factor: 0.01 },
        m: { label: 'Meters (m)', factor: 1 },
        km: { label: 'Kilometers (km)', factor: 1000 },
        in: { label: 'Inches (in)', factor: 0.0254 },
        ft: { label: 'Feet (ft)', factor: 0.3048 },
        yd: { label: 'Yards (yd)', factor: 0.9144 },
        mi: { label: 'Miles (mi)', factor: 1609.344 },
      },
    },
    weight: {
      label: 'Weight',
      units: {
        mg: { label: 'Milligrams (mg)', factor: 0.001 },
        g: { label: 'Grams (g)', factor: 1 },
        kg: { label: 'Kilograms (kg)', factor: 1000 },
        t: { label: 'Metric tons (t)', factor: 1000000 },
        oz: { label: 'Ounces (oz)', factor: 28.349523125 },
        lb: { label: 'Pounds (lb)', factor: 453.59237 },
      },
    },
    temperature: {
      label: 'Temperature',
      units: {
        c: { label: 'Celsius (°C)' },
        f: { label: 'Fahrenheit (°F)' },
        k: { label: 'Kelvin (K)' },
      },
    },
    volume: {
      label: 'Volume',
      units: {
        ml: { label: 'Milliliters (ml)', factor: 0.001 },
        l: { label: 'Liters (l)', factor: 1 },
        tsp: { label: 'US teaspoons (tsp)', factor: 0.00492892159375 },
        tbsp: { label: 'US tablespoons (tbsp)', factor: 0.01478676478125 },
        floz: { label: 'US fluid ounces (fl oz)', factor: 0.0295735295625 },
        cup: { label: 'US cups (cup)', factor: 0.2365882365 },
        pt: { label: 'US pints (pt)', factor: 0.473176473 },
        qt: { label: 'US quarts (qt)', factor: 0.946352946 },
        gal: { label: 'US gallons (gal)', factor: 3.785411784 },
      },
    },
  };

  function findScript() {
    return document.currentScript ||
      document.querySelector('script[src*="widgets/unit-converter.js"]');
  }

  function injectStyles() {
    if (document.getElementById(STYLE_ID)) return;
    var css =
      '.' + PREFIX + ', .' + PREFIX + ' * { box-sizing: border-box; }' +
      '.' + PREFIX + ' { position: relative; max-width: 520px; margin: 0 auto; padding: 24px 24px 30px;' +
      ' font-family: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;' +
      ' font-size: 16px; line-height: 1.5; color: #1f2937; background: #ffffff;' +
      ' border: 1px solid #e5e7eb; border-radius: 12px; }' +
      '.' + PREFIX + '__title { margin: 0 0 16px; font-size: 18px; font-weight: 600; color: #111827; }' +
      '.' + PREFIX + '__field { display: block; margin-bottom: 14px; }' +
      '.' + PREFIX + '__label { display: block; font-size: 13px; font-weight: 600; color: #6b7280; margin-bottom: 4px; }' +
      '.' + PREFIX + '__input, .' + PREFIX + '__select { width: 100%; padding: 9px 12px; font-size: 15px;' +
      ' font-family: inherit; color: #1f2937; background: #ffffff; border: 1px solid #d1d5db; border-radius: 8px; }' +
      '.' + PREFIX + '__input:focus, .' + PREFIX + '__select:focus { outline: 2px solid var(--hlw-accent); outline-offset: 1px; border-color: var(--hlw-accent); }' +
      '.' + PREFIX + '__row { display: flex; align-items: flex-end; gap: 10px; }' +
      '.' + PREFIX + '__row .' + PREFIX + '__field { flex: 1; min-width: 0; margin-bottom: 0; }' +
      '.' + PREFIX + '__swap { flex: 0 0 auto; width: 38px; height: 38px; margin-bottom: 0; padding: 0;' +
      ' border: 1px solid #d1d5db; border-radius: 8px; background: #ffffff; color: #6b7280;' +
      ' font-size: 18px; line-height: 1; cursor: pointer; }' +
      '.' + PREFIX + '__swap:hover { color: var(--hlw-accent); border-color: var(--hlw-accent); }' +
      '.' + PREFIX + '__swap:focus-visible { outline: 2px solid var(--hlw-accent); outline-offset: 2px; }' +
      '.' + PREFIX + '__result { margin-top: 16px; padding: 14px 16px; border-radius: 8px; background: #f9fafb;' +
      ' border: 1px solid #e5e7eb; font-size: 15px; color: #374151; }' +
      '.' + PREFIX + '__result-value { display: block; margin-top: 2px; font-size: 24px; font-weight: 700; color: var(--hlw-accent);' +
      ' overflow-wrap: anywhere; }' +
      '.' + PREFIX + '__credit { position: absolute; right: 10px; bottom: 6px; font-size: 11px;' +
      ' display: inline-flex; align-items: center; gap: 4px; color: #9ca3af; text-decoration: none; }' +
      '.' + PREFIX + '__credit svg { display: block; }' +
      '.' + PREFIX + '__credit:hover { color: #6b7280; text-decoration: underline; }' +
      '@media (max-width: 480px) { .' + PREFIX + ' { padding: 18px 16px 28px; } }';
    var style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = css;
    document.head.appendChild(style);
  }

  function el(tag, className, text) {
    var node = document.createElement(tag);
    if (className) node.className = className;
    if (text != null) node.textContent = text;
    return node;
  }

  function logoSvg() {
    var svgNS = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(svgNS, 'svg');
    svg.setAttribute('viewBox', '0 0 32 32');
    svg.setAttribute('width', '13');
    svg.setAttribute('height', '13');
    svg.setAttribute('aria-hidden', 'true');
    svg.setAttribute('focusable', 'false');
    function circle(cx, cy, r, attrs) {
      var c = document.createElementNS(svgNS, 'circle');
      c.setAttribute('cx', cx);
      c.setAttribute('cy', cy);
      c.setAttribute('r', r);
      for (var key in attrs) c.setAttribute(key, attrs[key]);
      svg.appendChild(c);
    }
    circle(16, 16, 16, { fill: '#0f0a0a' });
    circle(16, 16, 12, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1, opacity: 0.3 });
    circle(16, 16, 9, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1, opacity: 0.5 });
    circle(16, 16, 6, { fill: 'none', stroke: '#fff5f5', 'stroke-width': 1.2, opacity: 0.9 });
    circle(16, 16, 3, { fill: '#06b6d4' });
    circle(24.5, 7.5, 2, { fill: '#f97316' });
    circle(7, 16, 1.8, { fill: '#f97316' });
    circle(20, 20, 1.5, { fill: '#f97316' });
    return svg;
  }

  function convert(categoryKey, value, fromKey, toKey) {
    if (categoryKey === 'temperature') {
      var celsius = fromKey === 'c' ? value : fromKey === 'f' ? (value - 32) * 5 / 9 : value - 273.15;
      if (toKey === 'c') return celsius;
      if (toKey === 'f') return celsius * 9 / 5 + 32;
      return celsius + 273.15;
    }
    var units = CATEGORIES[categoryKey].units;
    return value * units[fromKey].factor / units[toKey].factor;
  }

  function formatNumber(n) {
    if (!isFinite(n)) return '—';
    var abs = Math.abs(n);
    var decimals = abs === 0 ? 0 : abs >= 100 ? 2 : abs >= 1 ? 4 : 6;
    var rounded = n.toFixed(decimals);
    // trim trailing zeros
    if (rounded.indexOf('.') !== -1) rounded = rounded.replace(/\.?0+$/, '');
    return rounded;
  }

  function build(script) {
    var defaultCategory = script.getAttribute('data-hl-default-category') || 'length';
    if (!CATEGORIES[defaultCategory]) {
      console.warn('[haynes lab unit-converter] Unknown data-hl-default-category "' + defaultCategory + '". Falling back to "length".');
      defaultCategory = 'length';
    }
    var accent = script.getAttribute('data-hl-accent') || '#f97316';

    injectStyles();

    var root = el('div', PREFIX);
    root.style.setProperty('--hlw-accent', accent);
    root.appendChild(el('h3', PREFIX + '__title', 'Unit Converter'));

    function makeField(labelText, control) {
      var field = el('label', PREFIX + '__field');
      field.appendChild(el('span', PREFIX + '__label', labelText));
      field.appendChild(control);
      return field;
    }

    var categorySelect = el('select', PREFIX + '__select');
    Object.keys(CATEGORIES).forEach(function (key) {
      var opt = el('option', null, CATEGORIES[key].label);
      opt.value = key;
      categorySelect.appendChild(opt);
    });
    categorySelect.value = defaultCategory;
    root.appendChild(makeField('Category', categorySelect));

    var input = el('input', PREFIX + '__input');
    input.type = 'number';
    input.step = 'any';
    input.value = '1';
    input.setAttribute('aria-label', 'Value to convert');
    root.appendChild(makeField('Value', input));

    var fromSelect = el('select', PREFIX + '__select');
    var toSelect = el('select', PREFIX + '__select');

    var swap = el('button', PREFIX + '__swap', '⇄');
    swap.type = 'button';
    swap.setAttribute('aria-label', 'Swap from and to units');

    var row = el('div', PREFIX + '__row');
    row.appendChild(makeField('From', fromSelect));
    row.appendChild(swap);
    row.appendChild(makeField('To', toSelect));
    root.appendChild(row);

    var result = el('div', PREFIX + '__result');
    result.setAttribute('aria-live', 'polite');
    var resultLabel = el('span', null, 'Result');
    var resultValue = el('span', PREFIX + '__result-value', '');
    result.appendChild(resultLabel);
    result.appendChild(resultValue);
    root.appendChild(result);

    function populateUnits() {
      var units = CATEGORIES[categorySelect.value].units;
      fromSelect.textContent = '';
      toSelect.textContent = '';
      Object.keys(units).forEach(function (key) {
        var fromOpt = el('option', null, units[key].label);
        fromOpt.value = key;
        fromSelect.appendChild(fromOpt);
        var toOpt = el('option', null, units[key].label);
        toOpt.value = key;
        toSelect.appendChild(toOpt);
      });
      var keys = Object.keys(units);
      fromSelect.value = keys[0];
      toSelect.value = keys.length > 1 ? keys[1] : keys[0];
    }

    function update() {
      var value = parseFloat(input.value);
      if (isNaN(value)) {
        resultValue.textContent = '—';
        return;
      }
      var converted = convert(categorySelect.value, value, fromSelect.value, toSelect.value);
      resultValue.textContent = formatNumber(converted) + ' ' + toSelect.value;
    }

    categorySelect.addEventListener('change', function () { populateUnits(); update(); });
    fromSelect.addEventListener('change', update);
    toSelect.addEventListener('change', update);
    input.addEventListener('input', update);
    swap.addEventListener('click', function () {
      var tmp = fromSelect.value;
      fromSelect.value = toSelect.value;
      toSelect.value = tmp;
      update();
    });

    populateUnits();
    update();

    var credit = el('a', PREFIX + '__credit');
    credit.appendChild(logoSvg());
    credit.appendChild(document.createTextNode('Powered by haynes lab'));
    credit.href = 'https://hayneslab.dev/tools/widgets/unit-converter';
    credit.target = '_blank';
    credit.rel = 'noopener';
    root.appendChild(credit);

    if (script.parentNode && script.parentNode.nodeName !== 'HEAD') {
      script.insertAdjacentElement('afterend', root);
    } else {
      document.body.appendChild(root);
    }
  }

  function init() {
    var script = findScript();
    if (!script) {
      console.warn('[haynes lab unit-converter] Could not locate its own script tag. Nothing rendered.');
      return;
    }
    build(script);
  }

  if (document.body) {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }
})();

</script>

Configuration

Every option is an attribute on the script tag — the same attributes the customizer above exposes. All attributes are optional unless marked required — defaults apply when omitted.

AttributeDefaultDescription
data-hl-default-category"length"Category shown on load: length, weight, temperature, or volume.
data-hl-accent"#f97316"Highlight color for the result and focus states.

Frequently asked questions

How do I install the Unit Converter?

Paste the script snippet where you want the converter to appear — it renders inline right after the tag and works immediately with all conversion tables built in, so no API key or backend is needed.

Can I change the default category and colors?

Yes — set data-hl-default-category to length, weight, temperature, or volume to pick the starting category, and data-hl-accent to change the highlight color.

Does it work on WordPress, Shopify, or Squarespace?

Yes — it is a single vanilla JS file with no dependencies, so it works on WordPress, Shopify, Squarespace, or any site that can embed a script tag.

More free widgets

Need a custom widget?

We build custom widgets, integrations, and whole products. Tell us what your site needs and we'll scope it.

Get in Touch