Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
I wanted to create a simple static website that would use JS to randomly rotate through a quotes.json file I maintain. My JavaScript experience is more limited as it's not what I do at work, so wha...
Question
javascript
#1: Initial revision
Vanilla JS Functions Review
I wanted to create a simple static website that would use JS to randomly rotate through a quotes.json file I maintain. My JavaScript experience is more limited as it's not what I do at work, so what I'm seeking is good JS practices and writing in a way that is "idiomatic" to the JS community. My other goals are to write it in a way where I can have decent test coverage and also avoid having to install dependencies, I'm using DigitalOcean's App Platform which allows for 3 free static sites. The goal is to not introduce anything that would require me to pay for the service. ``` const quoteText = document.getElementById("quote-text"); const quoteAuthor = document.getElementById("quote-author"); const quoteCitation = document.getElementById("quote-citation"); export async function fetchQuotes() { const response = await fetch('data/quotes.json'); if (!response.ok) { throw new Error(`Server returned ${response.status} ${response.statusText}`); } const data = await response.json(); if (!Array.isArray(data.quotes)) { throw new Error('Invalid data structure: missing quotes array'); } return data.quotes; } export function getRandomQuote(quotes) { const randomIndex = Math.floor(Math.random() * quotes.length); return quotes[randomIndex]; } function displayQuote(quoteObj) { quoteText.textContent = quoteObj.quote; quoteAuthor.textContent = quoteObj.author; quoteCitation.textContent = quoteObj.citation; } function scaleText() { const containerWidth = document.querySelector(".quote-container").clientWidth; const textWidth = quoteText.clientWidth; const scaleFactor = containerWidth / textWidth; if (scaleFactor < 1) { quoteText.style.transform = `scale(${scaleFactor})`; } else { quoteText.style.transform = "scale(1)"; } } async function populateQuote() { try { const quotes = await fetchQuotes(); const randomQuote = getRandomQuote(quotes); displayQuote(randomQuote); requestAnimationFrame(scaleText); window.addEventListener("resize", scaleText); } catch (error) { console.error(`Error loading quotes: ${error.message}`); } } // Load the initial quote populateQuote(); // Listen for click events on the "New Quote" button after DOM has loaded document.addEventListener('DOMContentLoaded', () => { document.querySelector('.btn').addEventListener('click', populateQuote); }) ```