CodingNic

Build the Currency Converter

Add Swap and Convert Actions

Build the Currency Converter 15 min read

Add Swap and Convert Actions

Add Swap and Convert Actions

The converter has two important actions: swapping the selected currencies and saving a conversion to history.

For swap, connect the existing button:

javascript
$("swapBtn").onclick = () => {
  [from, to] = [to, from];
  update();
};

For the Convert button, keep the workflow small. Re-render the current values, then save a history item:

javascript
function saveHistory() {
  const amount = Number($("amount").value) || 0;
  const item = {
    from,
    to,
    amount,
    result: amount * rate(from, to),
    date: new Date().toISOString()
  };

  const history = read("fx-history");
  write("fx-history", [item, ...history].slice(0, 30));
}

Then:

javascript
function convert() {
  update();
  saveHistory();
}

$("amount").oninput = update;
$("convertBtn").onclick = convert;

Checkpoint

Swap the pair, change the amount, and click Convert. The conversion should be saved even though the History screen has not been rendered yet.

Checkpoint

Refresh the page and inspect localStorage in DevTools. The fx-history key should contain your saved conversion.