Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created March 18, 2022 00:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3collective/8351591e7e38bb78f5b0c2cfba2922ba to your computer and use it in GitHub Desktop.
Save w3collective/8351591e7e38bb78f5b0c2cfba2922ba to your computer and use it in GitHub Desktop.
Currency converter with HTML & JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Currency converter with HTML &amp; JavaScript</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form>
<input id="amount" type="number" value="1" />
<select id="primary" class="input"></select>
<select id="secondary" class="input"></select>
<input id="btn-convert" type="button" value="Convert" />
</form>
<p id="result" style="display:none;">
<span id="txt-primary"></span>
<span id="txt-secondary"></span>
</p>
<script>
const currencies = {
AUD: "Australian Dollar",
CAD: "Canadian Dollar",
EUR: "Euro",
GBP: "British Pound",
INR: "Indian Rupee",
JPN: "Japanese Yen",
USD: "United States Dollar",
ZAR: "South African Rand",
};
const primaryCurrency = document.getElementById("primary");
const secondaryCurrency = document.getElementById("secondary");
primaryCurrency.innerHTML = getOptions(currencies);
secondaryCurrency.innerHTML = getOptions(currencies);
function getOptions(data) {
return Object.entries(data)
.map(([country, currency]) => `<option value="${country}">${country} | ${currency}</option>`)
.join("");
}
document.getElementById("btn-convert").addEventListener("click", fetchCurrencies);
function fetchCurrencies() {
const primary = primaryCurrency.value;
const secondary = secondaryCurrency.value;
const amount = document.getElementById("amount").value;
fetch("https://v6.exchangerate-api.com/v6/d14eeee6a4f935aab34c335e/latest/" + primary)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then((data) => {
console.log(data);
displayCurrency(data, primary, secondary, amount);
})
.catch((error) => console.error("FETCH ERROR:", error));
}
function displayCurrency(data, primary, secondary, amount) {
const calculated = amount * data.conversion_rates[secondary];
document.getElementById("result").setAttribute("style", "display:block");
document.getElementById("txt-primary").innerText = amount + " " + primary + " = ";
document.getElementById("txt-secondary").innerText = calculated + " " + secondary;
}
</script>
</body>
</html>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment