-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
320 lines (283 loc) · 12.1 KB
/
script.js
File metadata and controls
320 lines (283 loc) · 12.1 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
const apiKey = '204f26e69e034b7ea2bf87a86e1a90fa'; // chave de API RAWG
async function getGameImage(gameName) {
const url = `https://api.rawg.io/api/games?search=${encodeURI(gameName)}&key=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.results.length > 0 && data.results[0].background_image) {
return data.results[0].background_image;
} else {
return null;
}
} catch (error) {
console.error('Erro ao buscar imagem de jogo:', error);
return null;
}
}
async function getNewsImages(count) {
const url = `https://api.rawg.io/api/games?key=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
return data.results
.filter(game => game.background_image)
.slice(0, count)
.map(game => game.background_image);
} catch (error) {
console.error('Erro ao buscar imagens de notícias:', error);
return Array(count).fill('https://via.placeholder.com/500x300');
}
}
async function getAvatarImage(userName) {
const url = `https://api.rawg.io/api/games?search=${encodeURI(userName)}&key=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.results.length > 0 && data.results[0].background_image) {
return data.results[0].background_image;
} else {
return 'https://via.placeholder.com/80';
}
} catch (error) {
console.error('Erro ao buscar imagem de avatar:', error);
return 'https://via.placeholder.com/80';
}
}
// Script principal, executado quando o DOM estiver carregado
document.addEventListener('DOMContentLoaded', async () => {
const gameCards = document.querySelectorAll('.games-grid .game-card');
const gameNames = Array.from(gameCards).map(gameCard => {
return gameCard.querySelector('.game-info h3').textContent;
});
const gameImagePromises = gameNames.map(gameName => getGameImage(gameName));
const imageUrls = await Promise.all(gameImagePromises);
gameCards.forEach((gameCard, index) => {
const img = gameCard.querySelector('img');
if (imageUrls[index]) {
img.src = imageUrls[index];
}
});
const newsCards = document.querySelectorAll('.news-section .news-card');
const numNewsImagesNeeded = newsCards.length;
const newsImageUrls = await getNewsImages(numNewsImagesNeeded);
newsCards.forEach((newsCard, index) => {
const img = newsCard.querySelector('.news-image img');
if (newsImageUrls[index]) {
img.src = newsImageUrls[index];
img.onerror = () => { img.src = 'https://via.placeholder.com/500x300'; };
}
});
const testimonialCards = document.querySelectorAll('.testimonial-card');
const testimonialNames = Array.from(testimonialCards).map(card => {
return card.querySelector('.testimonial-content h4').textContent;
});
const avatarImagePromises = testimonialNames.map(name => getAvatarImage(name));
const avatarImageUrls = await Promise.all(avatarImagePromises);
testimonialCards.forEach((card, index) => {
const img = card.querySelector('.testimonial-avatar img');
if (avatarImageUrls[index]) {
img.src = avatarImageUrls[index];
img.onerror = () => { img.src = 'https://via.placeholder.com/80'; }; // Fallback
}
});
});
// Aguardar o carregamento do DOM
document.addEventListener('DOMContentLoaded', function() {
initMobileMenu(); // Menu mobile
initCountdown(); // Contador regressivo
initScrollAnimations(); // Animações ao scroll
initNewsletterForm(); // Validação do formulário de newsletter
});
function initMobileMenu() {
const mobileMenuBtn = document.querySelector('.mobile-menu');
const navMenu = document.querySelector('.nav-menu');
if (mobileMenuBtn && navMenu) {
mobileMenuBtn.addEventListener('click', function() {
navMenu.classList.toggle('active');
mobileMenuBtn.textContent = navMenu.classList.contains('active') ? '✕' : '☰';
});
// Fechar menu ao clicar em links
const navLinks = document.querySelectorAll('.nav-menu a');
navLinks.forEach(link => {
link.addEventListener('click', function() {
navMenu.classList.remove('active');
mobileMenuBtn.textContent = '☰';
});
});
// Fechar menu ao clicar fora
document.addEventListener('click', function(event) {
if (!event.target.closest('nav') && !event.target.closest('.mobile-menu')) {
navMenu.classList.remove('active');
mobileMenuBtn.textContent = '☰';
}
});
}
}
function initCountdown() {
const daysElement = document.getElementById('days');
const hoursElement = document.getElementById('hours');
const minutesElement = document.getElementById('minutes');
const secondsElement = document.getElementById('seconds');
if (daysElement && hoursElement && minutesElement && secondsElement) {
// Definir a data final da promoção (1 semana a partir de agora)
const currentDate = new Date();
const endDate = new Date();
endDate.setDate(currentDate.getDate() + 7);
// Atualizar o contador a cada segundo
function updateCountdown() {
const currentTime = new Date();
const diff = endDate - currentTime;
if (diff <= 0) {
// Promoção encerrada
daysElement.textContent = '00';
hoursElement.textContent = '00';
minutesElement.textContent = '00';
secondsElement.textContent = '00';
return;
}
// Calcular dias, horas, minutos e segundos
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
// Atualizar elementos do DOM
daysElement.textContent = days < 10 ? '0' + days : days;
hoursElement.textContent = hours < 10 ? '0' + hours : hours;
minutesElement.textContent = minutes < 10 ? '0' + minutes : minutes;
secondsElement.textContent = seconds < 10 ? '0' + seconds : seconds;
}
// Iniciar o contador
updateCountdown();
setInterval(updateCountdown, 1000);
}
}
function initScrollAnimations() {
const animateElements = document.querySelectorAll('.game-card, .news-card, .testimonial-card');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = '1';
entry.target.style.transform = 'translateY(0)';
}
});
}, { threshold: 0.1 });
animateElements.forEach(element => {
element.style.opacity = '0';
element.style.transform = 'translateY(50px)';
element.style.transition = 'opacity 0.7s ease, transform 0.7s ease';
observer.observe(element);
});
}
function initNewsletterForm() {
const newsletterForm = document.querySelector('.newsletter-form');
if (newsletterForm) {
newsletterForm.addEventListener('submit', function(event) {
event.preventDefault();
const nameInput = newsletterForm.querySelector('input[type="text"]');
const emailInput = newsletterForm.querySelector('input[type="email"]');
if (!nameInput.value.trim()) {
showFormError(nameInput, 'Por favor, informe seu nome.');
return;
}
if (!emailInput.value.trim()) {
showFormError(emailInput, 'Por favor, informe seu email.');
return;
}
if (!isValidEmail(emailInput.value)) {
showFormError(emailInput, 'Por favor, informe um email válido.');
return;
}
// Simulação de envio bem-sucedido
const formData = {
name: nameInput.value,
email: emailInput.value
};
console.log('Dados enviados:', formData);
showFormSuccess(newsletterForm, 'Inscrição realizada com sucesso! Obrigado por se juntar a nós.');
newsletterForm.reset();
});
}
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function showFormError(inputElement, message) {
removeFormError(inputElement);
const errorMessage = document.createElement('div');
errorMessage.className = 'form-error';
errorMessage.textContent = message;
errorMessage.style.color = 'red';
errorMessage.style.fontSize = '0.8rem';
errorMessage.style.marginTop = '0.3rem';
inputElement.classList.add('error');
inputElement.style.borderColor = 'red';
inputElement.parentNode.appendChild(errorMessage);
inputElement.focus();
}
function removeFormError(inputElement) {
inputElement.classList.remove('error');
inputElement.style.borderColor = '';
const errorMessage = inputElement.parentNode.querySelector('.form-error');
if (errorMessage) {
errorMessage.remove();
}
}
function showFormSuccess(form, message) {
const existingMessage = document.querySelector('.form-success');
if (existingMessage) {
existingMessage.remove();
}
const successMessage = document.createElement('div');
successMessage.className = 'form-success';
successMessage.textContent = message;
successMessage.style.color = '#4CAF50';
successMessage.style.padding = '1rem';
successMessage.style.marginTop = '1rem';
successMessage.style.backgroundColor = 'rgba(76, 175, 80, 0.1)';
successMessage.style.borderRadius = '5px';
successMessage.style.textAlign = 'center';
form.parentNode.appendChild(successMessage);
setTimeout(() => {
successMessage.remove();
}, 5000);
}
}
// Rolagem suave
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href');
const targetElement = document.querySelector(targetId);
if (targetElement) {
const headerOffset = document.querySelector('header').offsetHeight;
const elementPosition = targetElement.getBoundingClientRect().top;
const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
});
}
});
});
// Efeito de parallax para o hero
window.addEventListener('scroll', function() {
const heroSection = document.querySelector('.hero');
if (heroSection) {
const scrollPosition = window.pageYOffset;
heroSection.style.backgroundPositionY = scrollPosition * 0.5 + 'px';
}
});
// Animação de entrada para os elementos do hero
window.addEventListener('load', function() {
const heroContent = document.querySelector('.hero-content');
if (heroContent) {
setTimeout(() => {
heroContent.style.opacity = '1';
heroContent.style.transform = 'translateY(0)';
}, 300);
}
});
// Pré-estilização do hero content para animação
document.querySelector('.hero-content').style.opacity = '0';
document.querySelector('.hero-content').style.transform = 'translateY(30px)';
document.querySelector('.hero-content').style.transition = 'opacity 1s ease, transform 1s ease';