HTMLify
script.js
Views: 5 | Author: cody
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | const main = document.getElementById('main'); const addUserBtn = document.getElementById('add-user'); const doubleBtn = document.getElementById('double'); const showMillionairesBtn = document.getElementById('show-millionaires'); const sortBtn = document.getElementById('sort'); const calculateWealthBtn = document.getElementById('calculate-wealth'); let data = []; getRandomUser(); getRandomUser(); getRandomUser(); // Fetch random user and add money async function getRandomUser() { const res = await fetch('https://randomuser.me/api'); const data = await res.json(); const user = data.results[0]; const newUser = { name: `${user.name.first} ${user.name.last}`, money: Math.floor(Math.random() * 1000000) }; addData(newUser); } // Double eveyones money function doubleMoney() { data = data.map(user => { return { ...user, money: user.money * 2 }; }); updateDOM(); } // Sort users by richest function sortByRichest() { console.log(123); data.sort((a, b) => b.money - a.money); updateDOM(); } // Filter only millionaires function showMillionaires() { data = data.filter(user => user.money > 1000000); updateDOM(); } // Calculate the total wealth function calculateWealth() { const wealth = data.reduce((acc, user) => (acc += user.money), 0); const wealthEl = document.createElement('div'); wealthEl.innerHTML = `<h3>Total Wealth: <strong>${formatMoney( wealth )}</strong></h3>`; main.appendChild(wealthEl); } // Add new obj to data arr function addData(obj) { data.push(obj); updateDOM(); } // Update DOM function updateDOM(providedData = data) { // Clear main div main.innerHTML = '<h2><strong>Person</strong> Wealth</h2>'; providedData.forEach(item => { const element = document.createElement('div'); element.classList.add('person'); element.innerHTML = `<strong>${item.name}</strong> ${formatMoney( item.money )}`; main.appendChild(element); }); } // Format number as money - https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-string function formatMoney(number) { return '$' + number.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); } // Event listeners addUserBtn.addEventListener('click', getRandomUser); doubleBtn.addEventListener('click', doubleMoney); sortBtn.addEventListener('click', sortByRichest); showMillionairesBtn.addEventListener('click', showMillionaires); calculateWealthBtn.addEventListener('click', calculateWealth); |