-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
42 lines (37 loc) · 1.26 KB
/
script.js
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
document.addEventListener("DOMContentLoaded", () => {
const quoteBox = document.getElementById("quote");
const authorBox = document.getElementById("author");
const newQuoteBtn = document.getElementById("new-quote");
const categorySelect = document.getElementById("category");
let quotes = [];
// Fetch quotes from JSON file
fetch("quotes.json")
.then((response) => response.json())
.then((data) => {
quotes = data;
})
.catch((error) => console.error("Error loading quotes:", error));
const getQuote = (category = "all") => {
const filteredQuotes =
category === "all"
? quotes
: quotes.filter((q) => q.category === category);
if (filteredQuotes.length === 0) {
return {
text: "No quotes available for this category.",
author: "System",
};
}
const randomQuote =
filteredQuotes[Math.floor(Math.random() * filteredQuotes.length)];
return randomQuote;
};
const displayQuote = () => {
const category = categorySelect.value;
const quote = getQuote(category);
quoteBox.textContent = quote.text;
authorBox.textContent = `- ${quote.author}`;
};
newQuoteBtn.addEventListener("click", displayQuote);
categorySelect.addEventListener("change", displayQuote);
});