-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
99 lines (75 loc) · 2.63 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
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
97
98
99
// -------------------------------
// DOM ELEMENTS
// -------------------------------
const
quoteCard = document.querySelector('.quote_card'),
quoteDisplay = document.querySelector('.quote_quote'),
authorDisplay = document.querySelector('.quote_author'),
newQuoteButton = document.querySelector('.quote_new-quote-btn'),
twitterButton = document.querySelector('.quote_twitter-btn'),
whatsAppButton = document.querySelector('.quote_whats-app')
loader = document.querySelector('.loader')
// -------------------------------
// CALLBACK FUNCTIONS
// -------------------------------
const spinnerShown = ()=>{
loader.hidden = false
quoteCard.hidden = true
}
const spinnerHidden = ()=>{
loader.hidden = true
quoteCard.hidden = false
}
const writeQuote = async (response) =>{
const
quoteArray = await response.json(),
randomQuote = quoteArray[Math.floor(Math.random() * quoteArray.length)]
// console.log('random qupote =>', randomQuote)
quoteCard.dataset.category = randomQuote.tag
quoteDisplay.innerHTML = randomQuote.text
authorDisplay.innerHTML = randomQuote.author
spinnerHidden()
}
const throwError = (response)=>{
console.log('resonse =>', response.status)
throw new Error('Uups, something going wrong - STATUSCODE: \n' + response.status)
}
// -------------------------------
// FETCHING
// -------------------------------
const getQuote = async ()=>{
spinnerShown()
const apiURL = 'https://jacintodesign.github.io/quotes-api/data/quotes.json'
try{
const response = await fetch(apiURL)
// console.log('response => \n', response.status)
response.ok
? writeQuote(response)
: throwError(response)
}
catch(error){
spinnerHidden()
quoteDisplay.innerHTML = error
authorDisplay.innerHTML = 'Admin'
}
}
getQuote()
// -------------------------------
// Event Listeners
// -------------------------------
newQuoteButton.addEventListener('click', ()=>{
location.reload()
})
twitterButton.addEventListener('click', ()=>{
const twitterUrl = `https://twitter.com/intent/tweet?text=${quoteDisplay.innerHTML} - ${authorDisplay.innerHTML}`;
window.open(twitterUrl, '_blank');
})
whatsAppButton.addEventListener('click', ()=>{
const
encodedText = encodeURIComponent(quoteDisplay.innerHTML),
encodedAuthor = encodeURIComponent(authorDisplay.innerHTML),
whatsAppUrl = `whatsapp://send?text=${encodedText}-${encodedAuthor}`
// console.log('encoded text =>', encodedText)
// console.log('encoded author', encodedAuthor)
location.href = whatsAppUrl
})