I'm doing a program which converts currencies and measures. To make the code more reusable I've created a function which shows the symbols on a dropdown and get the rate from an API. This is the code:
const firstDropdown = document.querySelector('.first-value');
const secondDropdown = document.querySelector('.second-value');
const firstSymbol = document.querySelector('.first-symbol-button');
const secondSymbol = document.querySelector('.second-symbol-button');
const firstInput = document.querySelector('.first-value-input');
const secondInput = document.querySelector('.second-value-input');
//FUNCTIONS
const showSymbolsAndGetRates = (event, symbol, rate) => {
if(event.target.tagName === 'A'){
symbol.innerText = event.target.innerText;
rate = currencies.rates[event.target.innerText];
};
return rate;
}
//get symbols and rates
let firstRate = 'ciao';
let secondRate = 'ciao';
firstDropdown.addEventListener('click', e => {
e.preventDefault();
showSymbolsAndGetRates(e, firstSymbol, firstRate);
// if(e.target.tagName === 'A'){
// firstSymbol.innerText = e.target.innerText;
// firstRate = currencies.rates[e.target.innerText];
// return firstRate;
// };
console.log(firstRate)
});
secondDropdown.addEventListener('click', e => {
e.preventDefault();
showSymbolsAndGetRates(e, secondSymbol, secondRate);
// if(e.target.tagName === 'A'){
// secondSymbol.innerText = e.target.innerText;
// secondRate = currencies.rates[e.target.innerText];
// }
// return secondRate;
console.log(secondRate)
});
As you can see the code in the function showSymbolsAndGetRates is the same as the commented code, which was the original code. The problem is that when I use the commented code the rate is returned without problems but when I use the function the rate does not change, so the console shows 'ciao' instead of the real rate. I'm new at programming and I have no idea of how to solve this problem without having to write code for every event.