Created
September 27, 2024 18:40
-
-
Save Duartemartins/b0d272ea00ae5bc4de4d5124ae691a8f to your computer and use it in GitHub Desktop.
JS script that updates the currency based on the user's location
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
// Function to map country code to currency symbol | |
function getCurrencySymbolFromCountry(countryCode) { | |
const currencyMap = { | |
'US': '$', // US Dollar | |
'CA': '$', // Canadian Dollar | |
'GB': '£' // British Pound | |
// Default to Euro for any other country | |
}; | |
return currencyMap[countryCode] || '€'; // Default to Euro if country code is not in the map | |
} | |
// Function to set the cached currency and update timestamp | |
function cacheCurrency(currency) { | |
try { | |
localStorage.setItem('cached_currency', currency); | |
localStorage.setItem('currency_cache_timestamp', new Date().getTime()); | |
} catch (e) { | |
// Handle localStorage error (if any) | |
} | |
} | |
// Function to update all elements with class "currency" | |
function updateCurrencyOnPage(currency) { | |
const currencyElements = document.getElementsByClassName('currency'); // Using getElementsByClassName() | |
if (currencyElements.length === 0) return; // Skip if no elements are found | |
// Loop through the HTMLCollection using indexing | |
for (let i = 0; i < currencyElements.length; i++) { | |
currencyElements[i].innerText = currency; // Replace with the new currency symbol | |
} | |
} | |
// Function to fetch user's geolocation and set currency | |
function fetchAndSetCurrency() { | |
fetch('https://ipwhois.app/json/') | |
.then(response => response.json()) | |
.then(data => { | |
if (!data.country_code) throw new Error('Country code not found'); | |
const currencySymbol = getCurrencySymbolFromCountry(data.country_code); // Get corresponding currency symbol | |
cacheCurrency(currencySymbol); // Cache the detected currency for future use | |
updateCurrencyOnPage(currencySymbol); // Update all elements on the page with the currency symbol | |
}) | |
.catch(() => { | |
updateCurrencyOnPage('€'); // Fallback to Euro in case of error | |
}); | |
} | |
// Function to initialize currency (from cache or API) | |
function initializeCurrency() { | |
const cachedCurrency = localStorage.getItem('cached_currency'); | |
if (cachedCurrency) { | |
updateCurrencyOnPage(cachedCurrency); // Use cached currency if available | |
} else { | |
fetchAndSetCurrency(); // Fetch from API if no cache | |
} | |
} | |
// Trigger the currency update when the DOM is fully loaded | |
document.addEventListener('DOMContentLoaded', function() { | |
initializeCurrency(); // Initialize the currency update when the DOM is loaded | |
}); | |
// Example to simulate dynamically adding currency elements after 2 seconds (for testing) | |
setTimeout(function() { | |
const newElement = document.createElement('span'); | |
newElement.classList.add('currency'); | |
newElement.innerText = '€'; // Initial value | |
document.body.appendChild(newElement); | |
initializeCurrency(); // Re-run the currency update for new elements | |
}, 2000); // Adds element after 2 seconds | |
</script> | |
<!-- Example existing element with class "currency" --> | |
<span class="currency">€</span> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment