I have problem with my bitcoin converter app. When I execute the function (which is linked to html button) called "converted", the first result is NaN, but after executing it again it works properly.
Live reload enabled.
index.js:39 NaN
index.js:26 218537
index.js:22 47628
index.js:39 0.0019946250104980264
index.js:22 47628
index.js:26 218537
I tried to use callback function in my code, to solve this problem, but it didn't change anything.
Here is the code:
let inputCash;
let exchangeRateEur;
let exchangeRatePln;
let afterConv;
function getRate(callback) {
$.getJSON( "https://api.coindesk.com/v1/bpi/currentprice/eur.json", function(data) {
exchangeRateEur = parseInt(data.bpi.EUR.rate_float);
console.log(exchangeRateEur);
});
$.getJSON( "https://api.coindesk.com/v1/bpi/currentprice/pln.json", function(data) {
exchangeRatePln = parseInt(data.bpi.PLN.rate_float);
console.log(exchangeRatePln);
});
callback();
}
function getInputValue() {
inputCash = document.getElementById("number").value;
}
function convert() {
if ((document.getElementById("btn").innerText === 'EUR -> BTC')) {
afterConv = inputCash / exchangeRateEur;
}
console.log(afterConv);
}
function converted() {
getRate(getInputValue);
convert();
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BTC Converter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="cointainer">
<h1 class="title">btc converter</h1>
<img src="gfx/btc.png" class="logo" alt="BTC Logo">
</div>
<div id="buttons" class="buttons">
<button class="button" id="btn" onclick="changeButton(this.id)">EUR -> BTC</button>
</div>
<div class="display" name="converter">
<input type="number" id="number" name="number">
<input type="button" value="convert" onclick="converted();">
<p>x</p>
</div>
<script src="index.js"></script>
</body>
</html>