-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
208 lines (181 loc) · 6.39 KB
/
Copy pathscript.js
File metadata and controls
208 lines (181 loc) · 6.39 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
const API_KEY = "d727cc29acda44c3a813a205e5e875ec";
const url = "https://newsapi.org/v2/everything?q=";
// DOM Elements
const menuBtn = document.querySelector(".menuBtn");
const mobileMenu = document.querySelector(".mobile");
const searchForm = document.getElementById("searchForm");
const searchFormMobile = document.getElementById("searchFormMobile");
const searchInput = document.getElementById("searchInput");
const searchInputMobile = document.getElementById("searchInputMobile");
const backToTopBtn = document.getElementById("back-to-top-btn");
const loadingContainer = document.getElementById("loading");
// Initialize the page
document.addEventListener('DOMContentLoaded', function() {
// Load initial news
fetchData("cryptocurrency").then(data => {
renderMain(data.articles);
hideLoading();
});
// Setup event listeners
setupEventListeners();
});
// Setup all event listeners
function setupEventListeners() {
// Mobile menu toggle
menuBtn.addEventListener("click", toggleMobileMenu);
// Search functionality
searchForm.addEventListener("submit", handleSearch);
searchFormMobile.addEventListener("submit", handleMobileSearch);
// Back to top button
window.addEventListener('scroll', toggleBackToTopButton);
backToTopBtn.addEventListener('click', scrollToTop);
// Close mobile menu when clicking outside
document.addEventListener('click', function(e) {
if (!mobileMenu.contains(e.target) && e.target !== menuBtn) {
mobileMenu.classList.add('hidden');
}
});
}
// Toggle mobile menu
function toggleMobileMenu() {
mobileMenu.classList.toggle("hidden");
document.body.style.overflow = mobileMenu.classList.contains("hidden") ? 'auto' : 'hidden';
}
// Fetch news data from API
async function fetchData(query) {
showLoading();
try {
const res = await fetch(`${url}${query}&apiKey=${API_KEY}`);
if (!res.ok) {
throw new Error(`Failed to fetch: ${res.status} ${res.statusText}`);
}
const data = await res.json();
return data;
} catch (error) {
// console.error("Error fetching data:", error);
showError("Failed to load news. Please try again later.");
return { articles: [] };
} finally {
hideLoading();
}
}
// Handle main search form submission
async function handleSearch(e) {
e.preventDefault();
if (!searchInput.value.trim()) return;
const data = await fetchData(searchInput.value);
renderMain(data.articles);
searchInput.value = '';
mobileMenu.classList.add('hidden');
}
// Handle mobile search form submission
async function handleMobileSearch(e) {
e.preventDefault();
if (!searchInputMobile.value.trim()) return;
const data = await fetchData(searchInputMobile.value);
renderMain(data.articles);
searchInputMobile.value = '';
mobileMenu.classList.add('hidden');
}
// Render news articles to the page
function renderMain(articles) {
if (!articles || articles.length === 0) {
showError("No articles found. Try a different search term.");
return;
}
// Sort articles by published date (newest first)
articles.sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
let mainHTML = '';
articles.forEach(article => {
if (article.urlToImage) {
mainHTML += `
<div class="card fade-in">
<a href="${article.url}" target="_blank" rel="noopener noreferrer">
<img src="${article.urlToImage}" alt="${article.title}" loading="lazy" />
<div class="card-content">
<h4>${article.title || 'No title available'}</h4>
<div class="publishbyDate">
<p>${article.source?.name || 'Unknown source'}</p>
<span>•</span>
<p>${new Date(article.publishedAt).toLocaleDateString()}</p>
</div>
<div class="desc">
${article.description || 'No description available'}
</div>
</div>
</a>
</div>
`;
}
});
document.querySelector("main").innerHTML = mainHTML;
}
// Search function for category buttons
async function Search(query) {
const data = await fetchData(query);
renderMain(data.articles);
mobileMenu.classList.add('hidden');
}
// Show loading spinner
function showLoading() {
loadingContainer.style.display = 'flex';
}
// Hide loading spinner
function hideLoading() {
loadingContainer.style.display = 'none';
}
// Show error message
function showError(message) {
document.querySelector("main").innerHTML = `
<div class="error-message">
<p>${message}</p>
</div>
`;
}
// Back to top button functionality
function toggleBackToTopButton() {
if (window.scrollY > 300) {
backToTopBtn.style.display = 'block';
} else {
backToTopBtn.style.display = 'none';
}
}
function scrollToTop(e) {
e.preventDefault();
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
// Typing animation for search placeholder
const typingStrings = ["Bitcoin", "Ethereum", "Blockchain", "Crypto News"];
let currentStringIndex = 0;
let currentCharIndex = 0;
let isDeleting = false;
let typingSpeed = 100;
let deletingSpeed = 60;
function typeAnimation() {
const currentString = typingStrings[currentStringIndex];
if (isDeleting) {
if (currentCharIndex > 0) {
searchInput.placeholder = currentString.substring(0, currentCharIndex - 1);
currentCharIndex--;
setTimeout(typeAnimation, deletingSpeed);
} else {
isDeleting = false;
currentStringIndex = (currentStringIndex + 1) % typingStrings.length;
setTimeout(typeAnimation, typingSpeed);
}
} else {
if (currentCharIndex < currentString.length) {
searchInput.placeholder = currentString.substring(0, currentCharIndex + 1);
currentCharIndex++;
setTimeout(typeAnimation, typingSpeed);
} else {
isDeleting = true;
setTimeout(typeAnimation, 2000); // Pause at end of word
}
}
}
// Start typing animation
typeAnimation();