forked from AnujShrivastava01/AnimateItNow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
359 lines (319 loc) · 11.5 KB
/
script.js
File metadata and controls
359 lines (319 loc) · 11.5 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Function for displaying FAQ categories
function displaycategory(category){
const general=document.getElementById('general-faq');
const technical=document.getElementById('technical-faq');
if(category==='general'){
general.style.display='block';
technical.style.display='none';
}
else if(category==='technical'){
general.style.display='none';
technical.style.display='block';
}
}
// Service worker registration removed to fix 404 error
// if ('serviceWorker' in navigator) {
// window.addEventListener('load', () => {
// navigator.serviceWorker.register('/sw.js').then((registration) => {
// console.log('Service Worker registered:', registration);
//
// registration.onupdatefound = () => {
// const newWorker = registration.installing;
// newWorker.onstatechange = () => {
// if (
// newWorker.state === 'installed' &&
// navigator.serviceWorker.controller
// ) {
// console.log('New version available. Reloading...');
// window.location.reload();
// }
// };
// };
// }).catch((error) => {
// console.error('Service Worker registration failed:', error);
// });
// });
// }
function typewriter(){
const el=document.getElementById("modify");
if(!el)return;
const text=el.textContent;
el.textContent='';
let index=0;
let interval=setInterval(()=>{
if(index<text.length){
el.textContent+=text.charAt(index);
index++;
}
else{
clearInterval(interval);
}
},100);
}
typewriter();
// Function to make the FAQ collapsible
function toggleFAQ(element) {
if (!document.querySelector(".faq-item")) return
const faqItem = element.closest(".faq-item") //to make sure we can click anywhere
const isActive = faqItem.classList.contains("active")
// Close all other FAQ items
document.querySelectorAll(".faq-item.active").forEach((item) => {
if (item !== faqItem) {
item.classList.remove("active")
}
})
// Toggle current item
faqItem.classList.toggle("active", !isActive)
}
// Make toggleFAQ globally accessible
window.toggleFAQ = toggleFAQ
// Global (or module-level) variables to store animation and listener references for snake cursor
let currentAnimationId = null
let currentMousemoveListener = null
let snakeContainerElement = null // Keep a reference to the container element
// Removed the problematic 'const lucide = { createIcons: () => {}, }' declaration.
// The actual 'lucide' object is provided by the external script loaded in HTML.
// Declaring it as 'const' here prevented the global 'lucide' from being used.
// Moved cursor functions outside DOMContentLoaded for better scope and reusability
const isMobile = window.matchMedia("(max-width: 768px)").matches
function enableSnakeCursor() {
// Always ensure a clean slate before enabling.
// This is crucial for persistence across page navigations (especially with bfcache).
disableSnakeCursor()
snakeContainerElement = document.createElement("div") // Assign to global variable
snakeContainerElement.id = "cursor-snake"
document.body.appendChild(snakeContainerElement)
const dots = []
const dotCount = 20
for (let i = 0; i < dotCount; i++) {
const dot = document.createElement("div")
dot.className = "snake-dot"
snakeContainerElement.appendChild(dot) // Append to the new global container
dots.push({ el: dot, x: 0, y: 0 })
}
let mouseX = window.innerWidth / 2
let mouseY = window.innerHeight / 2
// Store event listener reference in a global variable
currentMousemoveListener = (e) => {
mouseX = e.clientX
mouseY = e.clientY
}
document.addEventListener("mousemove", currentMousemoveListener)
function animateSnake() {
let x = mouseX,
y = mouseY
dots.forEach((dot, i) => {
dot.x += (x - dot.x) * 0.2
dot.y += (y - dot.y) * 0.2
dot.el.style.left = dot.x + "px"
dot.el.style.top = dot.y + "px"
dot.el.style.transform = `scale(${1 - i / dotCount})`
x = dot.x
y = dot.y
})
// Store the animation ID in a global variable
currentAnimationId = requestAnimationFrame(animateSnake)
}
animateSnake()
}
function disableSnakeCursor() {
// Use the global reference to the container element
if (snakeContainerElement) {
if (currentAnimationId) {
cancelAnimationFrame(currentAnimationId)
currentAnimationId = null // Reset global ID
}
if (currentMousemoveListener) {
document.removeEventListener("mousemove", currentMousemoveListener)
currentMousemoveListener = null // Reset global listener
}
snakeContainerElement.remove() // Remove the cursor container
snakeContainerElement = null // Reset global reference
}
}
// Add event listener for page unload to ensure cleanup, especially for bfcache
window.addEventListener("pagehide", () => {
disableSnakeCursor()
})
window.addEventListener("DOMContentLoaded", () => {
// Theme toggle
const themeToggle = document.getElementById("theme-toggle")
const body = document.body
function setTheme(dark) {
const newIcon = dark ? "sun" : "moon"
body.classList.toggle("dark", dark) // Use 'dark' class for consistency
localStorage.setItem("theme", dark ? "dark" : "light")
// Replace icon completely
if (themeToggle) {
themeToggle.innerHTML = `<i data-lucide="${newIcon}"></i>`
// Only call lucide.createIcons() if the lucide object is actually available
if (window.lucide) {
window.lucide.createIcons()
}
}
}
const savedTheme = localStorage.getItem("theme")
setTheme(savedTheme === "dark")
themeToggle?.addEventListener("click", () => {
const isDark = body.classList.contains("dark") // Check for 'dark' class
setTheme(!isDark)
})
// Only call lucide.createIcons() if the lucide object is actually available
// This ensures icons are created on initial load if the library is ready.
if (window.lucide) {
window.lucide.createIcons()
}
// 🔽 Scroll Reveal Animation
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("visible")
// observer.unobserve(entry.target); // uncomment to animate only once
}
})
},
{ threshold: 0.2 },
)
document.querySelectorAll(".scroll-fade").forEach((el) => {
observer.observe(el)
})
// 🧪 Testimonial slider
const slider = document.getElementById("slider")
if (slider) {
const slides = document.querySelectorAll(".card")
let current = 0
function showSlide(index) {
const total = slides.length
if (index >= total) current = 0
else if (index < 0) current = total - 1
else current = index
slider.style.transform = `translateX(-${current * 100}%)`
}
function nextSlide() {
showSlide(current + 1)
}
setInterval(() => {
nextSlide()
}, 5000)
}
// 🧑💻 Contributors fetch
const contributorsGrid = document.getElementById("contributors-grid")
if (contributorsGrid) {
fetch("https://api.github.com/repos/itsAnimation/AnimateItNow/contributors")
.then((res) => res.json())
.then((contributors) => {
contributorsGrid.innerHTML = ""
contributors.forEach((contributor) => {
const card = document.createElement("a")
card.href = contributor.html_url
card.className = "contributor-card"
card.target = "_blank"
card.rel = "noopener noreferrer"
card.innerHTML = `
<img src="${contributor.avatar_url}" alt="${contributor.login}" class="contributor-avatar">
<h3>${contributor.login}</h3>
<p>Contributions: ${contributor.contributions}</p>
`
contributorsGrid.appendChild(card)
})
})
.catch((err) => {
console.error("Error fetching contributors:", err)
contributorsGrid.innerHTML = "<p>Could not load contributors at this time.</p>"
})
}
// 📨 Contact form validation
const contactForm = document.querySelector(".contact-form")
// Removed the problematic 'if (!contactForm) return;' line.
// This line was preventing the rest of the DOMContentLoaded block (including theme toggle and cursor logic)
// from executing on pages that do not have a .contact-form element.
const formInputs = contactForm ? contactForm.querySelectorAll("input[required], textarea[required]") : []
if (contactForm) {
function checkFormValidity() {
return [...formInputs].every((input) => input.value.trim() !== "")
}
contactForm.addEventListener("submit", (e) => {
e.preventDefault()
const allValid = checkFormValidity()
if (allValid) {
showToast("Message sent successfully!");
contactForm.reset()
} else {
alert("Please fill in all fields correctly. Fields cannot be empty or contain only spaces.")
}
})
formInputs.forEach((input) => {
input.addEventListener("input", () => {
const allFieldsFilled = checkFormValidity()
input.classList.toggle("invalid", !allFieldsFilled)
})
})
}
function showToast(message) {
const toast = document.createElement("div");
toast.className = "toast";
toast.textContent = message;
document.body.appendChild(toast);
// Trigger fade-in
setTimeout(() => toast.classList.add("show"), 100);
// Fade out and remove
setTimeout(() => {
toast.classList.remove("show");
setTimeout(() => toast.remove(), 300); // Wait for transition to finish
}, 3000);
}
// Snake cursor initialization and state management
const cursorToggle = document.getElementById("cursorToggle")
if (!isMobile && cursorToggle) {
// Read saved state from localStorage for initial setup
const savedCursorState = localStorage.getItem("cursorEnabled")
// Default to false if no state is saved, or use the saved state
const initialCursorEnabled = savedCursorState !== null ? JSON.parse(savedCursorState) : false
// Set initial state of the toggle checkbox
cursorToggle.checked = initialCursorEnabled
// Apply initial cursor state immediately
if (initialCursorEnabled) {
enableSnakeCursor()
} else {
disableSnakeCursor()
}
// Add event listener for changes to toggle cursor and save state
cursorToggle.addEventListener("change", function () {
if (this.checked) {
enableSnakeCursor()
localStorage.setItem("cursorEnabled", "true")
} else {
disableSnakeCursor()
localStorage.setItem("cursorEnabled", "false")
}
})
}
// 🚦 ProgressBar Functionality
function updateProgressBar() {
const windowScroll = document.body.scrollTop || document.documentElement.scrollTop
const documentHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight
const scrollPercent = (windowScroll / documentHeight) * 100
const progressBar = document.getElementById("progress-bar")
if (progressBar) {
progressBar.style.width = scrollPercent + "%"
}
}
window.addEventListener("scroll", updateProgressBar)
// Initialize on load
updateProgressBar()
})
// Scroll to top button functionality
// Show button when scrolled down
window.onscroll = function () {
const btn = document.getElementById("scrollBtn");
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
btn.classList.add("show");
} else {
btn.classList.remove("show");
}
};
// Scroll to top on click
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}