forked from Pranav-95/Random-Joke-Generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
76 lines (60 loc) · 2.35 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
const body = document.querySelector("body");
const toggle = document.querySelector(".toggle");
const copy = document.querySelector("#copy_joke");
const popup=document.querySelector(".copy-popup");
const jokeContainer = document.getElementById("joke");
const btn = document.getElementById("btn");
const url = "https://icanhazdadjoke.com/slack";
let getJoke = () => {
jokeContainer.classList.remove("fade");
fetch(url)
.then((response) => response.json())
.then((user) => {
let j = user.attachments[0].text;
// console.log(user.attachments[0].text);
jokeContainer.textContent = j;
jokeContainer.classList.add("fade");
}).catch((error) => {
// jokeContainer.textContent = error.message;
// * check if browser is online or not
if(!window.navigator.onLine){
jokeContainer.textContent = "Error: Your browser is offline. \nPlease try again once you're connected to the internet.";
}else{
jokeContainer.textContent = "An Error Occurred: "+ error + ".\n Please try again";
jokeContainer.classList.add("fade");
}
});
}
// * whenever user gets online again, dont show him/her the user offline error, instead show him joke
window.addEventListener('online', () => {
// ! check if there's no error happening before browser becomes online again, only in that case getJoke, else remain joke as it is
// if(jokeContainer.textContent != regex(/^Some\sError\sOccurred\W/)){getJoke()};
getJoke()
});
btn.addEventListener("click", getJoke);
getJoke();
btn.addEventListener('click', function handleClick() {
btn.textContent = 'Get Another Joke';
});
// Fade in
setTimeout(function () {
jokeContainer.innerHTML = "Click the button to get a Joke"
jokeContainer.style.opacity = 1;
}, 500);
toggle.addEventListener("click", () => {
body.classList.toggle("dark")
? (toggle.firstElementChild.className = "far fa-sun")
: (toggle.firstElementChild.className = "far fa-moon");
});
copy.addEventListener("click", () => {
const text = jokeContainer.textContent;
navigator.clipboard.writeText(text);
popup.classList.add("fade-in-image");
setTimeout(function() {
popup.classList.remove("fade-in-image");
},3000);
copy.querySelector("i").className = "fa-solid fa-check"
setTimeout(function () {
copy.querySelector("i").className = "fa-regular fa-copy"
}, 1000);
});