-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.js
95 lines (75 loc) · 2.53 KB
/
search.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
import {createLinkList, fetchData, getUrlParam, createElement} from './functions.js';
import renderNavigation from './navigation.js';
async function init() {
outerSearchForm ();
innerSearchForm ();
}
function outerSearchForm (){
const search = getUrlParam('search');
getSearchResults(search);
}
function innerSearchForm (){
let searchForm = document.querySelector('#inner-search-form');
searchForm.addEventListener('submit', (event) => {
event.preventDefault();
let searchInput = event.target.elements['search-input'].value;
getSearchResults(searchInput);
event.target.reset();
})
}
async function getSearchResults(search){
const searchResults = document.querySelector('#search-results');
searchResults.innerHTML = '';
const searchPageTitle = createElement('h1', `Results, search phrase: ${search}`, 'page-title search-page-title');
searchResults.append(searchPageTitle);
const users = await fetchData(`https://jsonplaceholder.typicode.com/users?q=${search}`);
const posts = await fetchData(`https://jsonplaceholder.typicode.com/posts?q=${search}`);
const albums = await fetchData(`https://jsonplaceholder.typicode.com/albums?q=${search}`);
const formattedUsers = users.map(user => {
const formattedUser = {
id: user.id,
title: user.name,
}
return formattedUser;
});
renderSearchResults({
data: formattedUsers,
parentElement: searchResults,
title: 'Users',
path: 'user',
});
renderSearchResults({
data: posts,
parentElement: searchResults,
title: 'Posts',
path: 'post',
});
const params = {
data: albums,
parentElement: searchResults,
title: 'Albums',
path: 'album',
};
renderSearchResults(params);
}
function renderSearchResults(paramsObj) {
let { data, parentElement, title, path } = paramsObj;
const wrapper = createElement('div', '', 'search-result-wrapper');
parentElement.append(wrapper)
const wrapperTitle = createElement('h2', '', 'search-wrapper-title');
wrapper.append(wrapperTitle);
if (data.length > 0){
wrapperTitle.textContent = title + ':';
let params = {
data,
path,
listClasses: ['search-list'],
itemClasses: ['search-item']
}
const searchResultElement = createLinkList(params);
wrapper.append(searchResultElement);
}else {
wrapperTitle.textContent = 'No ' + title.toLowerCase() + '...';
}
}
init();