-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
91 lines (75 loc) · 2.35 KB
/
script.js
File metadata and controls
91 lines (75 loc) · 2.35 KB
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
// quote
const quoteText = document.querySelector(".quoteText");
const authorText = document.querySelector(".authorText");
// buttons
const favourite = document.querySelector(".favourite");
const favouriteIcon = document.querySelector(".fa-heart");
const next = document.querySelector(".next");
const nextIcon = document.querySelector(".fa-forward-step");
// navbar
const navbar = document.querySelector(".navbar");
const navButton = document.querySelector(".navButton");
// api
const API = "https://api.api-ninjas.com/v1/quotes";
const API_KEY = "J2ICniv/elWwchmFyDflKA==JOre6csUV9gtHltw";
// local storage key
let uniqueKey = `quote-${Date.now()}`;
let currentQuote = "";
let currentAuthor = "";
fetchQuotes();
// fetch quotes
async function fetchQuotes() {
quoteText.textContent = "Fetching Quote...";
authorText.textContent = " ~ Fetching Author...";
try {
const response = await fetch(API, {
method: "GET",
headers: {
"X-Api-Key": API_KEY,
},
});
const data = await response.json();
const quoteObj = data[0];
const quote = quoteObj.quote;
const author = quoteObj.author;
if (quote.length >= 200) {
// console.log(quote.length);
fetchQuotes();
} else {
// console.log(quote.length);
quoteText.textContent = quote;
authorText.textContent = "~ " + author;
// local storage
currentAuthor = author;
currentQuote = quote;
}
} catch (error) {
quoteText.textContent = error;
console.error(error);
}
}
// fetch next quote
next.addEventListener("click", () => {
fetchQuotes();
uniqueKey = `quote-${Date.now()}`;
});
// add to favourite
favourite.addEventListener("click", () => {
localStorage.setItem(
uniqueKey,
JSON.stringify({
quote: currentQuote,
author: currentAuthor,
})
);
});
// nav button working
navButton.addEventListener("click", () => {
navbar.classList.toggle("active");
// console.log(navbar.classList);
if (navButton.classList.contains("fa-chevron-right")) {
navButton.classList.replace("fa-chevron-right", "fa-chevron-left");
} else {
navButton.classList.replace("fa-chevron-left", "fa-chevron-right");
}
});