-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
578 lines (502 loc) · 17.6 KB
/
script.js
File metadata and controls
578 lines (502 loc) · 17.6 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/* =====================================================
SCRIPT.JS — Globe logic, pins, tooltips, game, stars
Personal Portfolio — Avneet Kaur
===================================================== */
/* =====================================================
1. STAR BACKGROUND GENERATOR
Creates tiny CSS-animated stars scattered across the
fixed background layer (#stars-container).
===================================================== */
(function generateStars() {
const container = document.getElementById('stars-container');
const STAR_COUNT = 150;
for (let i = 0; i < STAR_COUNT; i++) {
const star = document.createElement('div');
star.classList.add('star');
// Random size: 1–3 px
const size = Math.random() * 2 + 1;
// Random position anywhere on the page
const x = Math.random() * 100;
const y = Math.random() * 100;
// Random animation duration and delay
const duration = (Math.random() * 4 + 2).toFixed(1); // 2–6 s
const delay = (Math.random() * 6).toFixed(1); // 0–6 s
const opacity = (Math.random() * 0.5 + 0.2).toFixed(2); // 0.2–0.7
star.style.cssText = `
width: ${size}px;
height: ${size}px;
left: ${x}%;
top: ${y}%;
--duration: ${duration}s;
--delay: ${delay}s;
--max-opacity: ${opacity};
`;
container.appendChild(star);
}
})();
/* =====================================================
2. GLOBE LOCATION DATA
Each object represents a pin on the globe.
Coordinates are in decimal degrees (lat, lng).
===================================================== */
const LOCATIONS = [
{
id: 'punjab',
name: 'Punjab, India',
lat: 31.1471,
lng: 75.3412,
flag: '🇮🇳',
emoji: '🌱', // used in tooltip card
year: '2005 – 2024',
blurb: 'Punjab is where I grew up, messed up, learned a lot, and slowly started dreaming bigger.',
url: 'chapters/punjab.html'
},
{
id: 'cape-town',
name: 'Cape Town, South Africa',
lat: -33.9249,
lng: 18.4241,
flag: '🇿🇦',
emoji: '🌍',
year: 'March 2024 - May 2024',
blurb: 'My first living alone. Three months in CPT changed how I see the world AND how I see myself.',
url: 'chapters/cape-town.html'
},
{
id: 'bethlehem',
name: 'Bethlehem, Pennsylvania',
lat: 40.6259,
lng: -75.3705,
flag: '🇺🇸',
emoji: '🎓',
year: 'August 2024 - 2028?',
blurb: 'Moved here for my bachelors in CS & Business @ Lehigh University.',
url: 'chapters/bethlehem.html'
},
{
id: 'london-scotland',
name: 'England & Scotland, UK',
lat: 51.5074,
lng: -0.1278,
flag: '🇬🇧',
emoji: '🏰',
year: 'January 2025',
blurb: 'A real estate winter study abroad program in London and Edinburgh.',
url: 'chapters/london.html'
},
{
id: 'santiago',
name: 'Santiago, Chile',
lat: -33.4489,
lng: -70.6693,
flag: '🇨🇱',
emoji: '🌶️',
year: 'June 2025 - July 2025',
blurb: 'Interned @ WatGen, a climate tech startup. Found a chilean mother ❤️',
url: 'chapters/santiago.html'
},
{
id: 'canada',
name: 'Montreal & Toronto, Canada',
lat: 43.6532,
lng: -79.3832,
flag: '🇨🇦',
emoji: '🍁',
year: '2025 - 2026',
blurb: 'Visited Montreal with school in summer for 5 days, then returned solo to visit cousins for 2 weeks.',
url: 'chapters/canada.html'
}
];
/* =====================================================
3. TOOLTIP MANAGEMENT
A single tooltip div is reused for all pins.
Position is calculated to avoid going off-screen.
===================================================== */
const exploreClickSound = new Audio('assets/fahhh.mp3');
exploreClickSound.preload = 'auto';
const americaYeahSound = new Audio('assets/america-yeah.mp3');
americaYeahSound.preload = 'auto';
const tooltip = document.getElementById('globe-tooltip');
const ttEmoji = document.getElementById('tt-emoji');
const ttLocation = document.getElementById('tt-location');
const ttYear = document.getElementById('tt-year');
const ttBlurb = document.getElementById('tt-blurb');
const ttLink = document.getElementById('tt-link');
let tooltipHideTimer = null;
/**
* Show the tooltip near a given DOM element (the pin marker).
* Checks viewport edges and flips position as needed.
*
* @param {Object} data - Location data object from LOCATIONS array
* @param {HTMLElement} pinEl - The pin DOM element on the globe
*/
function showTooltip(data, pinEl) {
// Cancel any pending hide
if (tooltipHideTimer) {
clearTimeout(tooltipHideTimer);
tooltipHideTimer = null;
}
// Populate tooltip content
ttEmoji.textContent = data.emoji;
ttLocation.textContent = data.name;
ttYear.textContent = data.year;
ttBlurb.textContent = data.blurb;
ttLink.href = data.url;
ttLink.textContent = 'Explore This Chapter →';
// On mobile, let CSS handle positioning (fixed bottom)
const isMobile = window.innerWidth <= 768;
if (!isMobile) {
positionTooltipNearPin(pinEl);
}
tooltip.classList.add('visible');
}
/**
* Position tooltip near the pin, flipping left/right to stay on screen.
* @param {HTMLElement} pinEl
*/
function positionTooltipNearPin(pinEl) {
const rect = pinEl.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
const TT_W = 280; // approximate tooltip width
const TT_H = 220; // approximate tooltip height
const OFFSET = 16; // gap between pin and tooltip
// Reset inline styles
tooltip.style.left = '';
tooltip.style.right = '';
tooltip.style.top = '';
tooltip.style.bottom = '';
tooltip.style.transform = '';
const pinCenterX = rect.left + rect.width / 2;
const pinCenterY = rect.top + rect.height / 2;
// Horizontal: prefer right side, flip to left if near right edge
let left;
if (pinCenterX + OFFSET + TT_W < vw - 16) {
left = pinCenterX + OFFSET;
} else {
left = pinCenterX - OFFSET - TT_W;
}
// Vertical: center on pin, clamp to viewport
let top = pinCenterY - TT_H / 2;
top = Math.max(16, Math.min(top, vh - TT_H - 16));
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
}
/**
* Hide the tooltip after a short delay (lets user move from pin to tooltip).
*/
function hideTooltip() {
tooltipHideTimer = setTimeout(() => {
tooltip.classList.remove('visible');
}, 200);
}
// Keep tooltip visible when mouse is over it
tooltip.addEventListener('mouseenter', () => {
if (tooltipHideTimer) {
clearTimeout(tooltipHideTimer);
tooltipHideTimer = null;
}
});
tooltip.addEventListener('mouseleave', () => {
hideTooltip();
});
// Play sound when "Explore This Chapter" is clicked, then navigate
ttLink.addEventListener('click', (e) => {
e.preventDefault();
const dest = ttLink.href;
const sound = dest.includes('bethlehem') ? americaYeahSound : exploreClickSound;
sound.currentTime = 0;
sound.play();
setTimeout(() => {
window.location.href = dest;
}, 400);
});
/* =====================================================
4. GLOBE INITIALISATION
Uses Globe.gl loaded via CDN.
Earth texture + cloud layer + 5 HTML pin markers.
===================================================== */
/* =====================================================
Globe init — called directly since globe.gl is a
synchronous <script> in <head> and is guaranteed to
be available by the time this script executes at
the bottom of <body>. Using window.load caused
intermittent failures in some browsers.
===================================================== */
document.addEventListener('DOMContentLoaded', initGlobe);
function initGlobe() {
const container = document.getElementById('globe-container');
// Globe fills the full viewport — match the 100vh container
const width = container.clientWidth || window.innerWidth;
const height = container.clientHeight || window.innerHeight;
/* -- Create the Globe instance -- */
// Globe is loaded via CDN (globe.gl) — available on window at runtime
// eslint-disable-next-line no-undef
const globe = Globe({ animateIn: true })(container)
// Use https:// explicitly — protocol-relative URLs (//...) break when
// the page is opened via file:// protocol (they become file://unpkg.com/...)
.globeImageUrl('https://unpkg.com/three-globe/example/img/earth-blue-marble.jpg')
.bumpImageUrl('https://unpkg.com/three-globe/example/img/earth-topology.png')
.backgroundImageUrl('https://unpkg.com/three-globe/example/img/night-sky.png')
// Globe dimensions
.width(width)
.height(height)
// Atmosphere glow (amber/gold tint)
.atmosphereColor('#f4a261')
.atmosphereAltitude(0.18)
// HTML pin markers
.htmlElementsData(LOCATIONS)
.htmlElement(createPinElement)
.htmlAltitude(0.01); // Slight elevation above surface
/* -- Cloud Layer --
Add a separate Three.js mesh for the cloud sphere.
Rotates independently at a slow rate.
---------------------------------------------------------------- */
const CLOUDS_IMG_URL = 'https://unpkg.com/three-globe/example/img/earth-clouds.png';
const CLOUDS_ALT = 0.004; // altitude above globe surface
const CLOUDS_ROTATION_DEG = 0.4; // degrees per second
// Access the underlying Three.js scene + renderer via globe methods
const THREE = window.THREE; // Globe.gl bundles Three.js globally
if (THREE) {
new THREE.TextureLoader().load(CLOUDS_IMG_URL, (cloudsTexture) => {
const radius = globe.getGlobeRadius() * (1 + CLOUDS_ALT);
const clouds = new THREE.Mesh(
new THREE.SphereGeometry(radius, 75, 75),
new THREE.MeshPhongMaterial({
map: cloudsTexture,
transparent: true,
opacity: 0.3,
depthWrite: false
})
);
globe.scene().add(clouds);
// Rotate clouds every frame using requestAnimationFrame
// This avoids blocking the main thread
let lastTime = 0;
function rotateClouds(timestamp) {
const delta = (timestamp - lastTime) / 1000; // seconds
lastTime = timestamp;
// Convert deg/sec to radians
clouds.rotation.y += (CLOUDS_ROTATION_DEG * Math.PI / 180) * delta;
requestAnimationFrame(rotateClouds);
}
requestAnimationFrame(rotateClouds);
});
}
/* -- Auto-rotation --
Gentle auto-rotation resumes 3 seconds after user stops dragging.
---------------------------------------------------------------- */
const controls = globe.controls();
controls.autoRotate = true;
controls.autoRotateSpeed = 0.3;
controls.enableZoom = true;
controls.minDistance = 150;
controls.maxDistance = 600;
let autoRotateTimer = null;
// User starts dragging — pause rotation
container.addEventListener('mousedown', () => {
clearTimeout(autoRotateTimer);
controls.autoRotate = false;
});
container.addEventListener('touchstart', () => {
clearTimeout(autoRotateTimer);
controls.autoRotate = false;
}, { passive: true });
// User stops dragging — schedule resume after 3 seconds
container.addEventListener('mouseup', scheduleResumeRotation);
container.addEventListener('touchend', scheduleResumeRotation);
function scheduleResumeRotation() {
clearTimeout(autoRotateTimer);
autoRotateTimer = setTimeout(() => {
controls.autoRotate = true;
}, 3000);
}
/* -- Responsive resize --
Recalculate globe size when window resizes.
---------------------------------------------------------------- */
window.addEventListener('resize', () => {
globe
.width(container.clientWidth)
.height(container.clientHeight);
});
// Point the globe so Asia/Africa/Europe sit in the right half of the
// viewport — complementing the left-side hero text
globe.pointOfView({ lat: 15, lng: 55, altitude: 2.2 }, 1000);
}
/* =====================================================
5. PIN ELEMENT FACTORY
Creates the DOM element for each globe pin marker.
Attaches hover/touch events for tooltip.
===================================================== */
/**
* Creates a flag pin DOM element for a given location.
* @param {Object} d - Location data from LOCATIONS array
* @returns {HTMLElement}
*/
function createPinElement(d) {
const wrapper = document.createElement('div');
wrapper.classList.add('globe-pin');
wrapper.setAttribute('data-id', d.id);
wrapper.setAttribute('role', 'button');
wrapper.setAttribute('tabindex', '0');
wrapper.setAttribute('aria-label', `${d.name} — ${d.year}. Click to explore.`);
const flag = document.createElement('span');
flag.classList.add('pin-flag');
flag.setAttribute('aria-hidden', 'true');
flag.textContent = d.flag;
if (typeof twemoji !== 'undefined') twemoji.parse(flag, { folder: 'svg', ext: '.svg' });
wrapper.appendChild(flag);
/* Desktop: hover to show tooltip */
wrapper.addEventListener('mouseenter', () => showTooltip(d, wrapper));
wrapper.addEventListener('mouseleave', hideTooltip);
/* Mobile: tap to toggle tooltip */
wrapper.addEventListener('click', (e) => {
e.stopPropagation();
if (tooltip.classList.contains('visible')) {
tooltip.classList.remove('visible');
} else {
showTooltip(d, wrapper);
}
});
/* Keyboard: Enter/Space to show tooltip */
wrapper.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
showTooltip(d, wrapper);
}
});
return wrapper;
}
// Dismiss tooltip when clicking outside any pin (mobile)
document.addEventListener('click', (e) => {
if (!tooltip.contains(e.target) && !e.target.closest('.globe-pin')) {
tooltip.classList.remove('visible');
}
});
/* =====================================================
6. NEWSLETTER
Handled by the Beehiiv embedded iframe — no custom
JS validation needed here.
===================================================== */
/* =====================================================
7. GUESS GAME
Answer is "Germany" (also accept "Deutschland").
Wrong guesses rotate through fun messages.
Correct: fire confetti + show modal.
===================================================== */
const gameForm = document.getElementById('game-form');
const gameInput = document.getElementById('game-input');
const gameResult = document.getElementById('game-result');
const guessModal = document.getElementById('guess-modal');
const modalClose = document.getElementById('modal-close');
// Correct answers (case-insensitive)
const CORRECT_ANSWERS = ['germany', 'deutschland'];
// Rotating wrong-guess messages
const WRONG_MESSAGES = [
"Nope! But great taste 😄",
"Cold! Keep exploring 🗺️",
"Not even close... or are you? 👀",
"Interesting guess! Try again ✈️"
];
// Track which wrong message to show next (rotates through the list)
let wrongMsgIndex = 0;
gameForm.addEventListener('submit', (e) => {
e.preventDefault();
const guess = gameInput.value.trim().toLowerCase();
if (!guess) {
gameResult.textContent = 'Type a guess first! 🗺️';
gameResult.className = 'game-result';
return;
}
if (CORRECT_ANSWERS.includes(guess)) {
// ✅ CORRECT GUESS
handleCorrectGuess();
} else {
// ❌ WRONG GUESS — rotate through fun messages
gameResult.textContent = WRONG_MESSAGES[wrongMsgIndex % WRONG_MESSAGES.length];
gameResult.className = 'game-result wrong';
wrongMsgIndex++;
// Shake animation on the input
gameInput.style.animation = 'none';
// Trigger reflow to restart animation
void gameInput.offsetWidth;
gameInput.style.animation = '';
}
});
/**
* Handle a correct guess:
* 1. Fire confetti
* 2. Show the success modal
*/
function handleCorrectGuess() {
gameResult.textContent = '🎉 YOU GOT IT! Opening the celebration...';
gameResult.className = 'game-result correct';
// Fire confetti burst
fireConfetti();
// Show modal after a brief delay so confetti starts first
setTimeout(() => {
guessModal.classList.add('visible');
modalClose.focus();
}, 400);
}
/**
* Confetti animation using canvas-confetti CDN library.
* Fires two bursts from opposite corners for a party effect.
*/
function fireConfetti() {
const defaults = {
colors: ['#f4a261', '#e76f51', '#ffd700', '#ffffff', '#ff6b6b'],
zIndex: 3000
};
// Left burst
confetti({
...defaults,
particleCount: 80,
angle: 60,
spread: 55,
origin: { x: 0, y: 0.7 }
});
// Right burst
confetti({
...defaults,
particleCount: 80,
angle: 120,
spread: 55,
origin: { x: 1, y: 0.7 }
});
// Center cascade after short delay
setTimeout(() => {
confetti({
...defaults,
particleCount: 120,
spread: 90,
origin: { x: 0.5, y: 0.4 }
});
}, 250);
}
/* -- Modal close handlers -- */
// Close button
modalClose.addEventListener('click', closeModal);
// Click outside modal card
guessModal.addEventListener('click', (e) => {
if (e.target === guessModal) closeModal();
});
// Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && guessModal.classList.contains('visible')) {
closeModal();
}
});
function closeModal() {
guessModal.classList.remove('visible');
gameInput.value = '';
gameResult.textContent = '';
gameResult.className = 'game-result';
}
/* =====================================================
8. SMOOTH SCROLL POLYFILL CHECK
The CSS scroll-behavior: smooth handles most cases,
but this ensures anchor links behave nicely.
===================================================== */
// Already handled globally by `html { scroll-behavior: smooth }` in CSS.
// No JS needed unless polyfill required for older browsers.