-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
92 lines (56 loc) · 1.88 KB
/
app.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
// API--https://superheroapi.com/api/2071918619630152
const search=document.getElementById("search_bar");
const matches_list=document.getElementById("search_list");
const search_btn = document.getElementById("search_btn");
const fav_btn=document.getElementById("fav_btn");
// API calling and fetching characters
fetch(`https://akabab.github.io/superhero-api/api/all.json`
).then(response => {
return response.json();
}).then((data)=>{
return heroes.push(...data);
})
.catch((error) => {
console.log(error);
});
const heroes=[];
let id;
// pattern matching
function SearchMatches(text,heroes){
return heroes.filter(hero=>{
const rexex = new RegExp(text,"gi");
return hero.name.match(rexex);
});
}
// gives a list of characters that match the input typed
search.addEventListener("input",()=>{
const matches = SearchMatches(search.value,heroes);
const html = matches.map(hero=>{
return`<li class="matches" val="${hero.id}"> ${hero.name}</li>`;
}).join("");
if(search.value.length>0){
matches_list.style.display="flex";
matches_list.innerHTML=html;
}else{
matches_list.innerHTML="";
matches_list.style.display="none";
}
});
matches_list.addEventListener("click",(e)=>{
console.log("clicked");
const item = e.target;
id=item.getAttribute("val");
matches_list.style.display="none";
const search_item=item.innerHTML;
search.value=`${search_item}`;
})
// when the search button is clicked, it takes us to character description pages
search_btn.addEventListener("click",()=>{
console.log(search.value)
console.log(id,"id");
window.open(`hero.html?id=${id}`,"_blank");
})
// when the fav button is clicked, it takes us to favorites pages
fav_btn.addEventListener("click",()=>{
window.open("favlist.html","_blank");
})