Simple Search
document.getElementById('searchForm').addEventListener('submit', function (event) {
event.preventDefault();
performSearch();
});
function performSearch() {
const searchQuery = document.getElementById('searchQuery').value;
const apiKey = 'YOUR_GOOGLE_API_KEY';
const cx = 'YOUR_CUSTOM_SEARCH_ENGINE_ID';
const url = `https://www.googleapis.com/customsearch/v1?q=${encodeURIComponent(searchQuery)}&key=${apiKey}&cx=${cx}`;
fetch(url)
.then(response => response.json())
.then(data => displayResults(data.items))
.catch(error => console.error('Error:', error));
}
function displayResults(results) {
const searchResultsDiv = document.getElementById('searchResults');
searchResultsDiv.innerHTML = '';
if (results) {
results.forEach(result => {
const resultDiv = document.createElement('div');
const title = document.createElement('h3');
const link = document.createElement('a');
const snippet = document.createElement('p');
link.href = result.link;
link.textContent = result.title;
snippet.textContent = result.snippet;
title.appendChild(link);
resultDiv.appendChild(title);
resultDiv.appendChild(snippet);
searchResultsDiv.appendChild(resultDiv);
});
} else {
searchResultsDiv.innerHTML = 'No results found.';
}
}
0 Comments