This repository was archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
48 lines (42 loc) · 1.97 KB
/
script.js
File metadata and controls
48 lines (42 loc) · 1.97 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
const container = document.querySelector(".container");
const searchInput = document.getElementById("search-input");
const searchForm = document.getElementById("search-form");
const searchResults = document.getElementById("search-results");
async function performSearch(query) {
searchResults.textContent = "Searching...";
const duckDuckGoEndpoint = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json`;
try {
const response = await fetch(duckDuckGoEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
if (data.Results && data.Results.length > 0) {
searchResults.innerHTML = data.Results.map(result => {
return `
<div class="result-item">
<div class="result-text">
<a href="${result.FirstURL}" class="result-title" target="_blank">${result.Text}</a>
<p class="result-link">${result.FirstURL}</p>
</div>
</div>
`;
}).join("");
} else {
if(data.AbstractURL.length > 0){
console.log(data.AbstractURL)
console.log(data.AbstractSource)
searchResults.innerHTML = '<div class="result-item"><div class="result-text"><a href="'+data.AbstractURL+'" class="result-title" target="_blank">'+data.AbstractSource+'</a><p class="result-link">'+data.AbstractURL+'</p></div></div>';
}
}
} catch (error) {
console.error("Error fetching search results:", error);
searchResults.textContent = "Error fetching search results.";
}
}
searchForm.addEventListener("submit", async function(event) {
event.preventDefault();
const query = searchInput.value;
await performSearch(query);
history.pushState({}, "", `/search?q=${encodeURIComponent(query)}`);
});