-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
217 lines (174 loc) · 6.72 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
const categories = document.getElementById("btnGroup")
const form = document.getElementById("jokesForm")
const searchInput = document.getElementById('searchInput')
const jokes = document.querySelector(".jokes__list")
const favJokes = document.getElementById('favJokes')
const asideBtn = document.getElementById('asideBtn')
const favSection = document.getElementById('favSection')
const dark = document.getElementById('dark')
const deleteJokesBtn = document.getElementById('deleteJokesBtn')
asideBtn.addEventListener('click', () => {
favSection.classList.toggle('favourite__mobile')
dark.classList.toggle('dark__theme')
asideBtn.classList.toggle('opened')
})
deleteJokesBtn.addEventListener('click', () => {
jokes.innerHTML = ''
})
// Запрос по категориям + вывод категорий в HTML
fetch('https://api.chucknorris.io/jokes/categories')
.then(response => response.json())
.then(data => {
let list = data.map((category, i) => `<li class="form_radio_btn">
<input id=${`radio` + i} type="radio" name="jokesCategory" value=${category} >
<label for=${`radio` + i}>${category}</label>
</li>`).join("")
categories.innerHTML = list
})
// Отслеживание изменений формы для динамического появления инпута и категорий
form.addEventListener('change', (e) => {
const checked = document.querySelector('input[name=jokesField]:checked').value
if(checked === 'categories') {
categories.style.display = 'flex'
searchInput.style.display = 'none'
} else if (checked === 'search') {
categories.style.display = 'none'
searchInput.style.display = 'flex'
} else {
categories.style.display = 'none'
searchInput.style.display = 'none'
}
})
function createElements () {
}
// Функция которая создает новые карточки и вставляет их в контейнер
function createCard (data, container) {
const card = document.createElement('div')
const jokesContainer = document.createElement('div');
const infoContainer = document.createElement('div')
const jokesText = document.createElement('p')
const heart = document.createElement('img')
const message = document.createElement('img')
const id = document.createElement('a')
const update = document.createElement('p')
update.innerText = ` Last update: ${data.updated_at.split(" ")[0]}`
update.classList.add("jokes__update")
infoContainer.append(update)
id.innerHTML = `ID: ${data.id}`;
id.href = "#"
message.src = 'images/message.png'
message.classList.add('message__img')
card.classList.add("jokes__card")
heart.classList.add("like")
data.favourite = checkFavListJokes(data.id)
heart.src = !data.favourite ? 'images/Vector.svg' : 'images/heart.svg'
jokesText.innerText = data.value
jokesText.classList.add('joke__text')
infoContainer.classList.add('jokes__info-container')
jokesContainer.append(id)
jokesContainer.append(jokesText)
jokesContainer.classList.add('jokes__body')
jokesContainer.append(infoContainer)
card.append(heart)
card.append(message)
card.append(jokesContainer)
container.append(card)
if(data.categories.length) {
const category = document.createElement('p')
category.innerText = data.categories
category.classList.add("jokes__category")
infoContainer.append(category)
}
// Отслеживание клика на сердечко
heart.addEventListener('click' , (e) => {
data.favourite = checkFavListJokes(data.id)
if(data.favourite) {
removeFromLocalStorage(data.id);
heart.src = 'images/Vector.svg'
} else {
data.favourite = false
saveFavToStorage(data)
createCard(data, favJokes)
heart.src = 'images/heart.svg'
}
})
}
// Функция которая рендерит шутку и определяет откуда пришли данные
function renderJoke (data) {
if(data.result) {
data.result.forEach((joke) => {
createCard(joke, jokes)
})
} else {
createCard(data, jokes)
}
}
// Отслеживание добавления шутки в форме
form.addEventListener('submit', (e) => {
e.preventDefault()
const checked = document.querySelector('input[name=jokesField]:checked').value
let URL = 'https://api.chucknorris.io/jokes/'
if(checked === 'search') {
const search = document.getElementById('searchInput').value
URL += `search?query=${search}`
} else if (checked === 'categories') {
URL += `random?category=${document.querySelector('input[name=jokesCategory]:checked').value}`
} else if (checked === 'random') {
URL += 'random'
}
fetch(URL)
.then(response => response.json())
.then(data => {
console.log(data);
renderJoke(data)
})
})
// Функция которая сохраняет выбраные шутки в список "favourite"
function saveFavToStorage (joke) {
let parse = isJokesInLocalStorage ()
if(parse){
parse.push(joke)
const strJoke = JSON.stringify(parse)
localStorage.setItem("favourite", strJoke)
} else {
const arrJoke = JSON.stringify([joke])
localStorage.setItem("favourite", arrJoke)
}
}
// Функция которая проверяет есть ли шутки в localstorage и если есть возвращает их
function isJokesInLocalStorage () {
if(localStorage.getItem("favourite")){;
const parse = JSON.parse(localStorage.getItem("favourite"))
return parse
}
return false
}
function checkFavListJokes (id) {
let jokes = isJokesInLocalStorage()
if(jokes){
return jokes.some((favJoke) => favJoke.id === id)
}
return false
}
// Функция которая записывает шутки в localstorage. Вызывается при запуске программы
function renderFavToStorage () {
let parse = isJokesInLocalStorage ()
if(parse){
parse.forEach((card) => {
createCard(card, favJokes)
})
}
}
// Функция которая убирает шутку с localstorage
function removeFromLocalStorage(id) {
let jokes = isJokesInLocalStorage();
const filterJokes = jokes.filter(joke => joke.id !== id);
if(filterJokes.length) {
localStorage.setItem("favourite", JSON.stringify(filterJokes));
} else {
localStorage.setItem("favourite", "");
}
favJokes.innerHTML = "";
renderFavToStorage();
}
renderFavToStorage()