Quer aprender a criar um Conversor de Moedas moderno, responsivo e funcional? Neste tutorial, vamos construir um conversor que utiliza a ExchangeRate-API para obter taxas de câmbio em tempo real.
O que vamos criar?
Criaremos um conversor de moedas completo usando HTML, CSS e JavaScript. O usuário poderá:
✅ Selecionar moedas para conversão
✅ Digitar um valor e obter o resultado em tempo real
✅ Inverter as moedas com um clique
✅ Obter as taxas de câmbio atualizadas automaticamente
Estrutura do Projeto
Nosso projeto será composto por três arquivos principais:
-
index.html
→ Interface do usuário -
style.css
→ Estilos do conversor -
script.js
→ Lógica para converter moedas
Veja o projeto ao vivo no link abaixo:
Veja o vídeo no YouTube:
Passo 1 - Criando o HTML
Crie um arquivo chamado index.html
e adicione o seguinte código:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Conversor de Moedas</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h2>Conversor de Moedas</h2>
<div class="converter">
<div class="input-group">
<label for="amount">Valor:</label>
<input type="number" id="amount" placeholder="Digite o valor" min="0">
</div>
<div class="currency-group">
<div>
<label for="fromCurrency">De:</label>
<select id="fromCurrency"></select>
</div>
<button id="swap" title="Inverter moedas">⇆</button>
<div>
<label for="toCurrency">Para:</label>
<select id="toCurrency"></select>
</div>
</div>
<button id="convertBtn">Converter</button>
<div class="result">
<p id="exchangeRate"></p>
<input type="text" id="result" readonly>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Esse código cria a interface do usuário com um campo de entrada, seleção de moedas e um botão de conversão.
Passo 2 - Criando o CSS (Estilos)
Agora crie um arquivo chamado style.css
e adicione:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Arial', sans-serif;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #1e3c72, #2a5298);
color: #fff;
}
.container {
background: rgba(255, 255, 255, 0.1);
padding: 20px;
border-radius: 12px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
text-align: center;
width: 350px;
backdrop-filter: blur(10px);
}
h2 {
margin-bottom: 15px;
font-size: 22px;
}
.input-group, .currency-group {
margin-bottom: 15px;
}
input, select {
width: 100%;
padding: 10px;
margin-top: 5px;
border: none;
border-radius: 6px;
font-size: 16px;
}
button {
width: 100%;
padding: 12px;
font-size: 16px;
background: #ff9800;
border: none;
cursor: pointer;
border-radius: 6px;
font-weight: bold;
color: #fff;
transition: 0.3s;
}
button:hover {
background: #e68900;
}
#swap {
background: transparent;
font-size: 20px;
border: none;
cursor: pointer;
color: #fff;
transition: 0.3s;
}
#swap:hover {
transform: rotate(180deg);
}
.result {
margin-top: 10px;
}
#result {
text-align: center;
font-size: 18px;
background: rgba(255, 255, 255, 0.2);
border: none;
color: #fff;
font-weight: bold;
}
@media (max-width: 400px) {
.container {
width: 90%;
}
}
Esse CSS deixa o conversor com um design moderno e responsivo.
Passo 3 - Criando o JavaScript
Agora crie o arquivo script.js
e adicione o seguinte código:
const apiKey = "SUA_API_KEY"; // Substitua pela sua chave da ExchangeRate-API
const apiUrl = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/USD`;
const fromCurrency = document.getElementById("fromCurrency");
const toCurrency = document.getElementById("toCurrency");
const amount = document.getElementById("amount");
const result = document.getElementById("result");
const exchangeRateText = document.getElementById("exchangeRate");
const convertBtn = document.getElementById("convertBtn");
const swapBtn = document.getElementById("swap");
let exchangeRates = {};
// Carregar moedas na lista
async function loadCurrencies() {
try {
const response = await fetch(apiUrl);
const data = await response.json();
exchangeRates = data.conversion_rates;
for (let currency in exchangeRates) {
let option1 = document.createElement("option");
let option2 = document.createElement("option");
option1.value = currency;
option1.textContent = currency;
option2.value = currency;
option2.textContent = currency;
fromCurrency.appendChild(option1);
toCurrency.appendChild(option2);
}
fromCurrency.value = "USD";
toCurrency.value = "BRL";
} catch (error) {
console.error("Erro ao carregar moedas:", error);
}
}
// Converter moeda
function convertCurrency() {
const from = fromCurrency.value;
const to = toCurrency.value;
const value = parseFloat(amount.value);
if (isNaN(value) || value <= 0) {
alert("Digite um valor válido.");
return;
}
const rate = exchangeRates[to] / exchangeRates[from];
const convertedAmount = (value * rate).toFixed(2);
result.value = convertedAmount;
exchangeRateText.textContent = `1 ${from} = ${rate.toFixed(4)} ${to}`;
}
// Inverter moedas
swapBtn.addEventListener("click", () => {
[fromCurrency.value, toCurrency.value] = [toCurrency.value, fromCurrency.value];
convertCurrency();
});
// Converter ao clicar no botão
convertBtn.addEventListener("click", convertCurrency);
// Carrega moedas na inicialização
loadCurrencies();
Esse código busca as taxas de câmbio da API e realiza as conversões.
Obs: Entrar no site oficial da ExchangeRate-API e criar uma conta gratuita para gerar a API KEY e substituir no código JavaScript.
Se preferir os códigos estão no meu Repositório no GitHub.
Passo 4 - Como Hospedar Online?
Você pode hospedar gratuitamente no GitHub Pages ou em serviços como Netlify e Vercel.
1️⃣ Subir no GitHub
-
Acesse GitHub e crie um repositório.
-
Envie os arquivos
index.html
,style.css
escript.js
. -
Vá em Settings → Pages → Source e selecione "Deploy from Branch".
-
Pronto! Seu site estará disponível em
https://seu-usuario.github.io/seu-repositorio/
.
Conclusão
Neste tutorial, aprendemos a criar um Conversor de Moedas completo com HTML, CSS e JavaScript, utilizando uma API de taxas de câmbio.
Gostou do tutorial? Deixe seu comentário e compartilhe! 🚀
Comentários
Postar um comentário
Obrigado pelo seu feedback!