1

I'm working on this currency converting app and ufetching the API from https://exchangeratesapi.io/

The app works except it only fetches the API on refresh. I'm using onload in body tag.

Any idea how can I make it work on first load without refreshing?

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>JS Bin</title>
     
        <script type="text/javascript" src="indexCurrencyFirst.js" ></script>
        <script type="text/javascript" src="indexCurrency.js" ></script>
        <link rel="stylesheet" type="text/css" href="styleCurrency.css">  
        
</head>
<body onload="convertCurrencyRight()" >

    <nav>
      <ul class="navbar">
        <li id="logo"><img src="Assets/Logo_openCurren.svg"></li> 
        <li id="date">Fecha</li>
      </ul>
    </nav>
    <div class="wrapper" >
        <div id="containerFrom">
          <input id="fromQuantity" type="number" value="1" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()"/>
          <select id="from" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
           
            
          </select>
         </div>   
         <div id="arrow"><img src="Assets/Arrow.svg"> </div>

        <div id="containerTo"> 
         <input id="toQuantity" type="number" value="0" onchange="convertCurrencyLeft()" onkeyup="convertCurrencyLeft()"/>
          <select id="to"  onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
            <option value="EUR"  selected>EUR</option>
          </select>
        </div>
    </div>    
        
    <div class="wrapper"  >
        <div id="containerCValues">
            <p id="currentRateA"> 1 Eur = 0.89 Gbp  </p>
            <p id="currentRateB"> 1 Gbp = 1.12 Eur  </p>
        </div>
    </div>


</body>
</html>

My JS files

Loaded in head indexCurrencyFirst

//fill the select options with the available currencies      

fetch("https://api.exchangeratesapi.io/latest?base=")
      .then((resp) => resp.json())
      .then(function(data){
        var allRates = data.rates;
        var selectA = document.getElementById("from");
         var selectB = document.getElementById("to");
         allRates = Object.entries(allRates)

         
         for(var i = 0; i < allRates.length; i++) {
            var opt = allRates[i][0];
            var el = document.createElement("option");
            el.textContent = opt;
            el.value = opt;
             if(opt==="GBP"){
                 var selectedAtt=document.createAttribute("selected");
                 el.setAttributeNode(selectedAtt);
             }
            selectA.appendChild(el);
             
            var la = document.createElement("option");
             la.textContent = opt;
             la.value = opt;
             selectB.appendChild(la);
        }   
     
        })
        
        .catch(function(error) {
        console.log(error);
        });

and the functions which convert the rates

function convertCurrencyRight() {
    var fromCurrency = document.getElementById("from").value;
    var toCurrency = document.getElementById("to").value;
    console.log(toCurrency);

    fetch("https://api.exchangeratesapi.io/latest?base=" + fromCurrency)
      .then((resp) => resp.json())
      .then(function(data){
        //if both currencies are the same return identical values
        (fromCurrency===toCurrency) ? 
        (document.getElementById("toQuantity").value = document.getElementById("fromQuantity").value,
        document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + "...",
        document.getElementById("currentRateB").textContent= "")
        :
        //otherwise return the top value as the multiplication of top currency rate by the amount specied below
        (document.getElementById("toQuantity").value = (data.rates[toCurrency]*document.getElementById("fromQuantity").value).toFixed(3),
        //change the single amount values
        document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + (data.rates[toCurrency]).toFixed(6) + " " + toCurrency,
        document.getElementById("currentRateB").textContent= "1 " + toCurrency + " = " + (1/data.rates[toCurrency]).toFixed(6) + " " + fromCurrency)
        //load the date of the current rates
        var date = document.getElementById("date");
        date.innerHTML = "LAST UPDATED " +
        data.date.split("-").reverse().join("-");
        

        })
    
        .catch(function(error) {
        console.log(error);
        });
}


function convertCurrencyLeft() {
    ...
}

Any idea how to fix this. I tried using jQuery with document ready instead of onload with luck

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Try to add the script to the bottom before `

    ` like ``. jQuery doc ready should've worked I'm not sure how you did it.

    – Kubwimana Adrien Sep 19 '19 at 15:58
  • Actually jQuery works the only problem was that EUR was not recognised as currency by the API since it is the base currency. Thanks for your help guys. Had such a long frustrating day – silver_hoodlum Sep 19 '19 at 16:22

1 Answers1

0

I'd just get ride of the onload on your body tag and just go with Jquery $(document).ready() and put your call to `convertCurrencyRight() there. In my fiddle this appears to work fine.

$(document).ready(function() {
    convertCurrencyRight();
});
bgaynor78
  • 454
  • 2
  • 7