const amountInput = document.getElementById('amount'); const fromCurrency = document.getElementById('fromCurrency'); const toCurrency = document.getElementById('toCurrency'); const swapButton = document.getElementById('swapButton'); const convertButton = document.getElementById('convertButton'); const resultDiv = document.getElementById('result'); // Status konversi otomatis let autoConvert = false; // Tombol Convert ditekan convertButton.addEventListener('click', () => { autoConvert = true; // Aktifkan auto-convert convertCurrency(); // Lakukan konversi convertButton.style.display = 'none'; // Sembunyikan tombol Convert }); // Swap mata uang swapButton.addEventListener('click', () => { const temp = fromCurrency.value; fromCurrency.value = toCurrency.value; toCurrency.value = temp; if (autoConvert) { convertCurrency(); // Konversi otomatis saat swap } else { clearResult(); // Hapus hasil jika auto-convert tidak aktif } }); // Pantau perubahan pada input dan dropdown [amountInput, fromCurrency, toCurrency].forEach((element) => { element.addEventListener('input', () => { if (autoConvert) { convertCurrency(); // Konversi otomatis saat ada input } }); element.addEventListener('change', () => { autoConvert = false; // Nonaktifkan auto-convert convertButton.style.display = 'block'; // Tampilkan tombol Convert clearResult(); // Hapus hasil sebelumnya }); }); // Fungsi konversi async function convertCurrency() { const amount = parseFloat(amountInput.value); const from = fromCurrency.value; const to = toCurrency.value; // Validasi input if (!amount || amount <= 0) { resultDiv.innerHTML = 'Please enter a valid amount.'; return; } try { const apiKey = '3ebe2ccf9eeea2aaef280201'; const url = `https://v6.exchangerate-api.com/v6/${apiKey}/latest/${from}`; const response = await fetch(url); const data = await response.json(); if (data.result === 'success') { const rate = data.conversion_rates[to]; const convertedAmount = (amount * rate).toFixed(2); resultDiv.innerHTML = `${amount} ${from} = ${convertedAmount} ${to}`; } else { resultDiv.innerHTML = `Error: ${data['error-type']}`; } } catch (error) { resultDiv.innerHTML = 'Error fetching conversion rate.'; console.error(error); } } // Fungsi untuk menghapus hasil konversi function clearResult() { resultDiv.innerHTML = ''; }