-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
96 lines (70 loc) · 2.68 KB
/
Copy pathapp.js
File metadata and controls
96 lines (70 loc) · 2.68 KB
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
const searchForm = document.getElementById("search-form");
const searchInput = document.getElementById("search-input");
const searchResults = document.getElementById("search-results");
console.log(searchForm);
console.log(searchInput);
console.log(searchResults);
//Theme Toggler Elements
const themeToggler = document.getElementById("theme-toggler");
const body = document.body;
async function searchWikipedia(query) {
const encodedQuery = encodeURIComponent(query);
const endpoint = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&
utf8=&format=json&origin=*&srlimit=10&srsearch=${encodedQuery}`;
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error("Failed to fetch results from Wikipedia API");
}
const json = await response.json();
return json;
}
function displayResults(results) {
searchResults.innerHTML = "";
results.forEach((result) => {
const url = "https://en.wikipedia.org/?curid=${results.pageid}";
const titleLink = `<a href="${url}" target="_blank" rel="noopener"> ${result.title} </a>`;
const urlLink = `<a href="${url} class="result-link" target="_blank" rel="noopener">${url}</a>`;
const resultItem = document.createElement("div");
resultItem.className = "result-item";
resultItem.innerHTML = `
<h3 class="result-title">${titleLink}</h3>
${urlLink}
<p class="result-snippet">${result.snippet}</p>
`;
searchResults.appendChild(resultItem);
});
}
searchForm.addEventListener('submit', async (e) => {
e.preventDefault();
const query = searchInput.value.trim();
if (!query) {
searchResults.innerHTML = "<p>Please enter a valid search term.</p>";
return;
}
searchResults.innerHTML = "<div class='spinner'> Loading... </div>";
try {
const results = await searchWikipedia(query);
if (results.query.searchinfo.totalhits === 0) {
searchResults.innerHTML = "<p> No Results Found </p>";
}
else {
displayResults(results.query.search);
}
}
catch (error) {
console.error(error);
searchResults.innerHTML = "<p> An error occurred while fetching results. Please try again later. </p>";
}
});
themeToggler.addEventListener("click", () => {
body.classList.toggle("dark-theme");
if (body.classList.contains("dark-theme")) {
themeToggler.textContent = "Dark";
themeToggler.style.background = "#fff";
themeToggler.style.color = "#333";
} else {
themeToggler.textContent = "Light";
themeToggler.style.border = "2px solid #ccc";
themeToggler.style.color = "#333";
}
})