forked from Ashutosh102/AniStream-X
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhome.js
81 lines (68 loc) · 2.72 KB
/
home.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
//Code for homepage
const errorContainer = document.createElement("div");
errorContainer.style.color = "red";
fetch('https://animxer-api-cvxg.vercel.app/anime/gogoanime/top-airing')
.then(response => response.json())
.then(data => {
var cardDiv = document.getElementById("card");
data.results.slice(0, 20).forEach(anime => {
var animeDiv = document.createElement("div");
animeDiv.style.display = "inline-block";
animeDiv.style.marginBottom = "20px";
animeDiv.style.width = "300px";
var title = anime.title;
var shortTitle = title.substring(0, 50);
if (title.length > 50)
shortTitle += "...";
animeDiv.innerHTML = `<img height="350" width="250" src="${anime.image}" alt="${anime.title}"> <a href="/anime.html?id=${anime.id}"> <h2>${shortTitle}</h2> </a> `;
cardDiv.appendChild(animeDiv);
});
})
.catch(error => {
errorContainer.innerText = "Error loading. Please refresh";
document.body.appendChild(errorContainer);
});
//Code for searching the last query the user made
const queryInput = document.getElementById("query");
if (localStorage.getItem("query")) {
queryInput.value = localStorage.getItem("query");
}
queryInput.addEventListener("input", function () {
localStorage.setItem("query", this.value);
});
//Code which fetches API and displays autocomplete results
const autocompleteResults = document.getElementById("autocomplete-results");
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn(...args);
timeoutId = null;
}, delay);
};
}
const debouncedInput = debounce(function (event) {
autocompleteResults.innerHTML = "";
const query = document.querySelector("#query").value;
fetch('https://animxer-api-cvxg.vercel.app/anime/gogoanime/' + query)
.then(response => response.json())
.then(data => {
data.results.slice(0, 4).forEach(result => {
const li = document.createElement("li");
li.innerText = result.title;
li.addEventListener("click", function (event) {
window.location.href = `/anime.html?id=${result.id}`;
});
autocompleteResults.appendChild(li);
});
});
}, 500);
queryInput.addEventListener("input", debouncedInput);
document.addEventListener("click", function (event) {
if (event.target !== autocompleteResults) {
autocompleteResults.innerHTML = "";
}
});