-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
77 lines (63 loc) · 1.86 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
//endpoint and request
const endpoint = "https://icanhazdadjoke.com/";
const request = new XMLHttpRequest();
//selectors
const button = document.querySelector("button");
const buttonCtaSelector = document.getElementById("cta");
const jokeSection = document.getElementById("joke");
const errorContainer = document.getElementById("error-container");
const errorMsg = document.getElementById("error-message");
const loader = document.getElementById("loader");
const setDisabledUIState = (isDisabled) => {
if (isDisabled) {
setLoaderState(false);
setButtonState(false);
} else {
setButtonState(true);
setLoaderState(true);
}
};
const showJoke = (joke) => {
setDisabledUIState(true);
jokeSection.innerHTML = joke;
};
const showError = (error) => {
setDisabledUIState(true);
errorContainer.style.display = "block";
errorMsg.innerHTML = error;
};
const setLoaderState = (isVisible) => {
const displayState = isVisible ? "block" : "none";
loader.style.display = displayState;
};
const setButtonState = (isDisabled) => {
if (isDisabled) {
button.setAttribute("disabled", "disabled");
} else {
button.removeAttribute("disabled");
}
const buttonState = isDisabled ? "none" : "block";
buttonCtaSelector.style.display = buttonState;
};
const setButtonCta = (isError) => {
const buttonCta = isError ? "Please try again" : "Get another joke!";
buttonCtaSelector.innerHTML = buttonCta;
};
const getJoke = () => {
request.open("GET", endpoint);
request.setRequestHeader("Accept", "application/json");
request.responseType = "json";
request.onload = () => {
showJoke(request.response.joke);
setButtonCta(false);
};
request.onerror = () => {
showError("An error occured, please try again.");
setButtonCta(true);
};
request.send();
};
button.addEventListener("click", () => {
setDisabledUIState(false);
getJoke();
});