Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1310 lines (1310 loc) · 59.9 KB
/
Copy pathscript.js
File metadata and controls
1310 lines (1310 loc) · 59.9 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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/**
* Cradlepoint Amazon Storefront - Main TypeScript
* Dropdown nav + button ripple + product card hover + enhanced scroll selectors
*/
// ============================================================================
// IIFE — Keeps all state private, identical runtime behavior to original JS
// ============================================================================
(function () {
// ==========================================================================
// STATE & CONFIGURATION
// ==========================================================================
let currentTestimonialIndex = 0;
let testimonialInterval = null;
let touchStartX = 0;
let touchEndX = 0;
const TESTIMONIAL_INTERVAL_MS = 5000;
const SCROLL_OBSERVER_THRESHOLD = 0.15;
const CART_ANIMATION_DURATION = 300;
const STICKY_HEADER_HEIGHT = 84;
const PRODUCT_STAGGER_DELAY = 100;
const TOUCH_SWIPE_THRESHOLD = 75;
const EASING_BOUNCE = 'cubic-bezier(0.34, 1.56, 0.64, 1)';
const EASING_SMOOTH = 'cubic-bezier(0.4, 0, 0.2, 1)';
// Store observers for cleanup
const observers = [];
// Detect reduced motion preference (live -- updates if user changes setting)
let prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
motionQuery.addEventListener('change', (e) => {
prefersReducedMotion = e.matches;
});
// ==========================================================================
// UTILITY FUNCTIONS
// ==========================================================================
/**
* Returns a scoped rAF-based throttle function.
* Each call to createThrottle() produces an independent gate,
* so multiple consumers (sticky header, comparison table, etc.)
* never block each other.
*/
function createThrottle() {
let ticking = false;
return function throttle(callback) {
if (ticking)
return;
ticking = true;
requestAnimationFrame(() => {
callback();
ticking = false;
});
};
}
function smoothScrollTo(element, offset = STICKY_HEADER_HEIGHT) {
if (!element)
return;
const elementPosition = element.getBoundingClientRect().top + window.scrollY;
const offsetPosition = elementPosition - offset;
window.scrollTo({
top: offsetPosition,
behavior: prefersReducedMotion ? 'auto' : 'smooth'
});
}
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// ==========================================================================
// TAB NAVIGATION
// ==========================================================================
function initTabNavigation() {
const tabs = document.querySelectorAll('.brand-nav__tab');
// Only observe actual page sections, not nav elements that happen to have data-section
const sections = document.querySelectorAll('section[data-section], div[data-section]:not(.brand-nav__tab):not(.brand-nav__dropdown-link)');
if (!tabs.length)
return;
// Add tablist role to the container
const tabContainer = document.querySelector('.brand-header__nav, .brand-nav');
if (tabContainer) {
tabContainer.setAttribute('role', 'tablist');
}
// Add keyboard navigation support with roving tabindex
tabs.forEach((tab, index) => {
tab.setAttribute('role', 'tab');
// Only the active tab (or first tab if none active) gets tabindex 0
const isActive = tab.classList.contains('brand-nav__tab--active');
tab.setAttribute('tabindex', isActive || (index === 0 && !document.querySelector('.brand-nav__tab--active')) ? '0' : '-1');
// Click handler
tab.addEventListener('click', (e) => {
const href = tab.getAttribute('href');
// If href points to another page, allow default browser navigation
if (href && !href.startsWith('#')) {
const currentPage = window.location.pathname.split('/').pop() || 'index.html';
const linkPage = href.split('#')[0];
if (linkPage && linkPage !== currentPage) {
return; // Allow navigation to other page
}
}
e.preventDefault();
activateTab(tab);
});
// Keyboard handler
tab.addEventListener('keydown', (e) => {
const keyEvent = e;
if (keyEvent.key === 'Enter' || keyEvent.key === ' ') {
keyEvent.preventDefault();
activateTab(tab);
}
// Arrow key navigation with roving tabindex
if (keyEvent.key === 'ArrowRight') {
keyEvent.preventDefault();
const nextTab = tabs[index + 1] || tabs[0];
tab.setAttribute('tabindex', '-1');
nextTab.setAttribute('tabindex', '0');
nextTab.focus();
}
if (keyEvent.key === 'ArrowLeft') {
keyEvent.preventDefault();
const prevTab = tabs[index - 1] || tabs[tabs.length - 1];
tab.setAttribute('tabindex', '-1');
prevTab.setAttribute('tabindex', '0');
prevTab.focus();
}
});
});
function activateTab(tab) {
const targetSection = tab.getAttribute('data-section');
// Update active tab with roving tabindex
tabs.forEach((t) => {
t.classList.remove('brand-nav__tab--active');
t.setAttribute('aria-selected', 'false');
t.setAttribute('tabindex', '-1');
});
tab.classList.add('brand-nav__tab--active');
tab.setAttribute('aria-selected', 'true');
tab.setAttribute('tabindex', '0');
// Scroll to section (use specific selector to avoid matching nav elements)
if (targetSection) {
const section = document.querySelector(`section[data-section="${targetSection}"], div[data-section="${targetSection}"]:not(.brand-nav__tab)`);
if (section) {
smoothScrollTo(section);
}
}
}
// Update active tab on scroll with improved threshold
const sectionObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
const sectionName = entry.target.getAttribute('data-section');
const activeTab = document.querySelector(`.brand-nav__tab[data-section="${sectionName}"]`);
if (activeTab) {
tabs.forEach((t) => {
t.classList.remove('brand-nav__tab--active');
t.setAttribute('aria-selected', 'false');
t.setAttribute('tabindex', '-1');
});
activeTab.classList.add('brand-nav__tab--active');
activeTab.setAttribute('aria-selected', 'true');
activeTab.setAttribute('tabindex', '0');
}
}
});
}, {
threshold: [0.5, 0.75],
rootMargin: `-${STICKY_HEADER_HEIGHT + 20}px 0px -30% 0px`
});
sections.forEach((section) => {
sectionObserver.observe(section);
});
observers.push(sectionObserver);
// HANDLE INITIAL SCROLL POSITION - Set correct active tab on page load
function setInitialActiveTab() {
const scrollY = window.scrollY;
// If page is scrolled on load, find which section is visible
if (scrollY > 100) {
let activeSection = null;
let maxVisibility = 0;
sections.forEach((section) => {
const rect = section.getBoundingClientRect();
const viewportHeight = window.innerHeight;
const visibleHeight = Math.min(rect.bottom, viewportHeight) - Math.max(rect.top, 0);
const visibilityRatio = visibleHeight / viewportHeight;
if (visibilityRatio > maxVisibility) {
maxVisibility = visibilityRatio;
activeSection = section;
}
});
if (activeSection) {
const sectionName = activeSection.getAttribute('data-section');
const correspondingTab = document.querySelector(`.brand-nav__tab[data-section="${sectionName}"]`);
if (correspondingTab) {
tabs.forEach((t) => {
t.classList.remove('brand-nav__tab--active');
t.setAttribute('aria-selected', 'false');
t.setAttribute('tabindex', '-1');
});
correspondingTab.classList.add('brand-nav__tab--active');
correspondingTab.setAttribute('aria-selected', 'true');
correspondingTab.setAttribute('tabindex', '0');
}
}
}
}
// Run on load and after a brief delay to handle browser scroll restoration
setInitialActiveTab();
setTimeout(setInitialActiveTab, 100);
}
// ==========================================================================
// "SEE MORE PRODUCTS" TOGGLE
// ==========================================================================
function initProductToggles() {
const toggleConfigs = [
{ buttonId: 'wwan-routers-see-more', containerId: 'wwan-routers-products' },
{ buttonId: 'wwan-adapters-see-more', containerId: 'wwan-adapters-products' }
];
toggleConfigs.forEach(({ buttonId, containerId }) => {
const button = document.getElementById(buttonId);
const container = document.getElementById(containerId);
if (!button || !container)
return;
const extraProducts = container.querySelectorAll('.product-card--extra');
let isExpanded = false;
let isAnimating = false;
// Set initial ARIA state
button.setAttribute('aria-expanded', 'false');
button.setAttribute('aria-controls', containerId);
// Click handler -- isAnimating guard prevents double-fire (no debounce needed)
const handleToggle = () => {
if (isAnimating)
return;
isAnimating = true;
isExpanded = !isExpanded;
button.setAttribute('aria-expanded', isExpanded.toString());
button.disabled = true; // Disable during animation
if (isExpanded) {
// Batch all display changes first to avoid layout thrashing
extraProducts.forEach((card) => {
card.style.display = 'block';
});
// Read layout ONCE after all display changes are applied
const parent = extraProducts.length
? extraProducts[0].parentElement
: null;
const computedStyle = parent
? window.getComputedStyle(parent)
: null;
const colString = computedStyle?.gridTemplateColumns || '';
const gridCols = colString ? colString.split(' ').length : 5;
// Show products with grid-aware staggered animation
extraProducts.forEach((card, cardIndex) => {
const htmlCard = card;
const columnIndex = cardIndex % gridCols;
setTimeout(() => {
if (prefersReducedMotion) {
htmlCard.style.opacity = '1';
htmlCard.style.transform = 'translateY(0)';
}
else {
htmlCard.classList.add('fade-in-up', 'visible');
}
}, columnIndex * PRODUCT_STAGGER_DELAY);
});
button.textContent = 'Show fewer products';
// Re-enable button after all column animations finish
const maxDelay = ((gridCols - 1) * PRODUCT_STAGGER_DELAY) + 400;
setTimeout(() => {
isAnimating = false;
button.disabled = false;
}, maxDelay);
}
else {
// Hide products with reverse stagger
const totalCards = extraProducts.length;
const lastCardDelay = (totalCards - 1) * 40;
extraProducts.forEach((card, index) => {
const htmlCard = card;
setTimeout(() => {
htmlCard.classList.remove('visible');
if (prefersReducedMotion) {
// Reset inline styles set during expand
htmlCard.style.opacity = '';
htmlCard.style.transform = '';
htmlCard.style.display = 'none';
}
}, index * 40);
});
button.textContent = 'See more products';
// Re-enable AFTER all individual card animations complete
const hideDelay = Math.max(lastCardDelay + 300, 500);
setTimeout(() => {
extraProducts.forEach((card) => {
const htmlCard = card;
htmlCard.style.display = 'none';
// Reset stale inline styles so next expand starts clean
htmlCard.style.opacity = '';
htmlCard.style.transform = '';
});
isAnimating = false;
button.disabled = false;
}, hideDelay);
}
};
button.addEventListener('click', handleToggle);
});
}
// ==========================================================================
// SCROLL ANIMATIONS
// ==========================================================================
function initScrollAnimations() {
const animatedElements = document.querySelectorAll('.story-card, .category-tile, .product-card:not(.product-card--extra), .stat-item, .testimonial, .peace-of-mind, .contact-cta, .from-manufacturer__item, .cert-badge, .category-banner, .btn--modern, .btn--gradient');
if (!animatedElements.length)
return;
// Skip animations if reduced motion is preferred
if (prefersReducedMotion) {
animatedElements.forEach((element) => {
const htmlEl = element;
htmlEl.style.opacity = '1';
htmlEl.style.transform = 'none';
});
return;
}
// WRITE PASS: add fade-in-up class to all elements first
animatedElements.forEach((element) => {
element.classList.add('fade-in-up');
});
// READ PASS: calculate grid-aware stagger delays (separated to prevent layout thrashing)
requestAnimationFrame(() => {
animatedElements.forEach((element) => {
const htmlEl = element;
const parent = htmlEl.parentElement;
if (parent?.classList.contains('story-cards') ||
parent?.classList.contains('category-grid') ||
parent?.classList.contains('product-grid') ||
parent?.classList.contains('stats-grid') ||
parent?.classList.contains('from-manufacturer__grid') ||
parent?.classList.contains('certifications-bar__badges')) {
// Get all visible siblings (not display:none)
const siblings = Array.from(parent.children).filter((child) => {
return window.getComputedStyle(child).display !== 'none';
});
const siblingIndex = siblings.indexOf(element);
// Calculate column position for responsive grids
const computedStyle = window.getComputedStyle(parent);
const colString = computedStyle.gridTemplateColumns || '';
const gridCols = colString ? colString.split(' ').length : 3;
const columnIndex = siblingIndex % gridCols;
// Stagger by column position (not total index)
htmlEl.style.transitionDelay = `${columnIndex * 0.08}s`;
}
});
});
// IntersectionObserver for triggering animations
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
observer.unobserve(entry.target);
}
});
}, {
threshold: SCROLL_OBSERVER_THRESHOLD,
rootMargin: '0px 0px -100px 0px'
});
animatedElements.forEach((element) => observer.observe(element));
observers.push(observer);
// HANDLE INITIAL VIEWPORT - Trigger animations for elements already visible on page load
requestAnimationFrame(() => {
animatedElements.forEach((element) => {
const rect = element.getBoundingClientRect();
const isInViewport = rect.top < window.innerHeight && rect.bottom > 0;
if (isInViewport) {
element.classList.add('visible');
}
});
});
}
// ==========================================================================
// STICKY BRAND HEADER
// ==========================================================================
function initStickyHeader() {
const brandHeaderEl = document.querySelector('.brand-header');
const amazonHeader = document.querySelector('.amazon-header');
if (!brandHeaderEl || !amazonHeader)
return;
const brandHeader = brandHeaderEl;
// Cache measurements -- recalculated on resize
let stickyThreshold = amazonHeader.offsetHeight;
let brandHeaderHeight = brandHeader.offsetHeight;
let isSticky = false;
const throttle = createThrottle();
// Apply sticky styles via JS since no CSS rule exists for brand-header--sticky
function applySticky() {
if (isSticky)
return;
isSticky = true;
brandHeader.classList.add('brand-header--sticky');
brandHeader.style.position = 'fixed';
brandHeader.style.top = '0';
brandHeader.style.left = '0';
brandHeader.style.width = '100%';
brandHeader.style.zIndex = '999';
brandHeader.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)';
document.body.style.paddingTop = brandHeaderHeight + 'px';
}
function removeSticky() {
if (!isSticky)
return;
isSticky = false;
brandHeader.classList.remove('brand-header--sticky');
brandHeader.style.position = '';
brandHeader.style.top = '';
brandHeader.style.left = '';
brandHeader.style.width = '';
brandHeader.style.zIndex = '';
brandHeader.style.boxShadow = '';
document.body.style.paddingTop = '0';
}
const handleScroll = () => {
throttle(() => {
if (window.scrollY > stickyThreshold) {
applySticky();
}
else {
removeSticky();
}
});
};
window.addEventListener('scroll', handleScroll, { passive: true });
// Recalculate cached measurements on resize
const handleResize = debounce(() => {
const wasSticky = isSticky;
if (wasSticky)
removeSticky();
stickyThreshold = amazonHeader.offsetHeight;
brandHeaderHeight = brandHeader.offsetHeight;
if (wasSticky && window.scrollY > stickyThreshold)
applySticky();
}, 200);
window.addEventListener('resize', handleResize, { passive: true });
// Check on init in case page loaded already scrolled
if (window.scrollY > stickyThreshold) {
applySticky();
}
}
// ==========================================================================
// BACK TO TOP
// ==========================================================================
function initBackToTop() {
const backToTopLink = document.querySelector('.footer__back-to-top-link');
if (!backToTopLink)
return;
backToTopLink.addEventListener('click', (e) => {
e.preventDefault();
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}
// ==========================================================================
// CART COUNTER ANIMATION
// ==========================================================================
function initCartCounter() {
const cartCount = document.querySelector('.amazon-header__cart-count');
// Only target "Add to Cart" buttons in product cards and FBT,
// NOT the comparison table "See options" buttons
const optionButtons = document.querySelectorAll('.product-card .btn--amazon, .fbt-pricing > .btn--amazon');
if (!cartCount || !optionButtons.length)
return;
let currentCount = parseInt(cartCount.textContent ?? '0', 10) || 0;
// Provide a live region for screen readers
cartCount.setAttribute('aria-live', 'polite');
cartCount.setAttribute('aria-atomic', 'true');
optionButtons.forEach((button) => {
button.addEventListener('click', (e) => {
e.preventDefault();
currentCount++;
cartCount.textContent = String(currentCount);
if (prefersReducedMotion) {
// Simple color flash only
cartCount.style.color = '#ff9900';
setTimeout(() => {
cartCount.style.color = '';
}, CART_ANIMATION_DURATION);
}
else {
// Premium bounce animation with proper easing
cartCount.style.transition = `transform 0.15s ${EASING_BOUNCE}, color 0.15s ${EASING_SMOOTH}`;
cartCount.style.transform = 'scale(1.15)';
cartCount.style.color = '#ff9900';
setTimeout(() => {
cartCount.style.transform = 'scale(1)';
cartCount.style.color = '';
}, CART_ANIMATION_DURATION);
}
});
});
}
// ==========================================================================
// TESTIMONIAL CAROUSEL
// ==========================================================================
function initTestimonialCarousel() {
const dots = document.querySelectorAll('.dot');
const testimonialSection = document.querySelector('.testimonials-section');
if (!dots.length)
return;
// Add ARIA attributes -- dots act as tab-like controls
const dotsContainer = document.querySelector('.dots-container, .testimonial-dots');
if (dotsContainer) {
dotsContainer.setAttribute('role', 'tablist');
dotsContainer.setAttribute('aria-label', 'Testimonial navigation');
}
dots.forEach((dot, index) => {
dot.setAttribute('role', 'tab');
dot.setAttribute('aria-label', `Show testimonial ${index + 1}`);
dot.setAttribute('tabindex', index === 0 ? '0' : '-1');
});
function updateActiveDot(index) {
dots.forEach((dot, i) => {
dot.classList.toggle('dot--active', i === index);
dot.setAttribute('aria-selected', i === index ? 'true' : 'false');
dot.setAttribute('tabindex', i === index ? '0' : '-1');
});
}
function nextTestimonial() {
currentTestimonialIndex = (currentTestimonialIndex + 1) % dots.length;
updateActiveDot(currentTestimonialIndex);
}
function prevTestimonial() {
currentTestimonialIndex = (currentTestimonialIndex - 1 + dots.length) % dots.length;
updateActiveDot(currentTestimonialIndex);
}
function resetInterval() {
if (testimonialInterval) {
clearInterval(testimonialInterval);
}
// Respect reduced motion - disable auto-advance
if (!prefersReducedMotion) {
testimonialInterval = setInterval(nextTestimonial, TESTIMONIAL_INTERVAL_MS);
}
}
// Dot click/keyboard handlers
dots.forEach((dot, index) => {
dot.addEventListener('click', () => {
currentTestimonialIndex = index;
updateActiveDot(index);
resetInterval();
});
dot.addEventListener('keydown', (e) => {
const keyEvent = e;
if (keyEvent.key === 'Enter' || keyEvent.key === ' ') {
keyEvent.preventDefault();
currentTestimonialIndex = index;
updateActiveDot(index);
resetInterval();
}
// Arrow key navigation between dots
if (keyEvent.key === 'ArrowRight') {
keyEvent.preventDefault();
const nextIndex = (index + 1) % dots.length;
dots[nextIndex].focus();
currentTestimonialIndex = nextIndex;
updateActiveDot(nextIndex);
resetInterval();
}
if (keyEvent.key === 'ArrowLeft') {
keyEvent.preventDefault();
const prevIndex = (index - 1 + dots.length) % dots.length;
dots[prevIndex].focus();
currentTestimonialIndex = prevIndex;
updateActiveDot(prevIndex);
resetInterval();
}
});
});
// TOUCH SWIPE SUPPORT for mobile
if (testimonialSection) {
// Touch handlers
testimonialSection.addEventListener('touchstart', (e) => {
const touchEvent = e;
touchStartX = touchEvent.changedTouches[0].screenX;
}, { passive: true });
testimonialSection.addEventListener('touchend', (e) => {
const touchEvent = e;
touchEndX = touchEvent.changedTouches[0].screenX;
handleSwipe();
}, { passive: true });
function handleSwipe() {
const swipeDistance = touchEndX - touchStartX;
if (Math.abs(swipeDistance) > TOUCH_SWIPE_THRESHOLD) {
if (swipeDistance > 0) {
// Swipe right - previous
prevTestimonial();
}
else {
// Swipe left - next
nextTestimonial();
}
resetInterval();
}
}
// Pause on hover
testimonialSection.addEventListener('mouseenter', () => {
if (testimonialInterval) {
clearInterval(testimonialInterval);
}
});
testimonialSection.addEventListener('mouseleave', () => {
resetInterval();
});
}
// Start auto-advance
resetInterval();
}
// ==========================================================================
// VIDEO THUMBNAILS & LOADING STATE
// ==========================================================================
function initVideoThumbnails() {
const thumbnails = document.querySelectorAll('.video-thumbnail');
const mainVideoContainer = document.querySelector('.video-section__main iframe');
const videoWrapper = document.querySelector('.video-section__main');
if (!thumbnails.length || !mainVideoContainer)
return;
// Add loading state handler for iframe
const loadingIndicator = document.createElement('div');
loadingIndicator.className = 'video-loading';
loadingIndicator.setAttribute('aria-hidden', 'true');
loadingIndicator.style.cssText = `
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
font-size: 14px;
opacity: 0;
transition: opacity 0.3s ease;
pointer-events: none;
z-index: 1;
`;
loadingIndicator.textContent = 'Loading video...';
if (videoWrapper) {
videoWrapper.style.position = 'relative';
videoWrapper.appendChild(loadingIndicator);
}
// Video URLs mapped to thumbnails (in order)
const videoUrls = [
'https://players.brightcove.net/5380177764001/default_default/index.html?videoId=6372048292112',
'https://players.brightcove.net/5380177764001/default_default/index.html?videoId=6372048292112'
];
// Show loading state on iframe load
mainVideoContainer.addEventListener('load', () => {
loadingIndicator.style.opacity = '0';
});
thumbnails.forEach((thumbnail, index) => {
const htmlThumbnail = thumbnail;
// Add keyboard accessibility
htmlThumbnail.setAttribute('role', 'button');
htmlThumbnail.setAttribute('tabindex', '0');
htmlThumbnail.setAttribute('aria-label', `Play video ${index + 1}`);
const clickHandler = () => {
if (mainVideoContainer && videoUrls[index]) {
// Show loading indicator
loadingIndicator.style.opacity = '1';
// Change iframe source
mainVideoContainer.src = videoUrls[index];
}
// Visual feedback with smooth easing
if (!prefersReducedMotion) {
htmlThumbnail.style.transition = `transform 0.2s ${EASING_SMOOTH}, opacity 0.2s ${EASING_SMOOTH}`;
htmlThumbnail.style.transform = 'scale(0.95)';
htmlThumbnail.style.opacity = '0.7';
setTimeout(() => {
htmlThumbnail.style.transform = 'scale(1)';
htmlThumbnail.style.opacity = '1';
}, 200);
}
};
htmlThumbnail.addEventListener('click', clickHandler);
htmlThumbnail.addEventListener('keydown', (e) => {
const keyEvent = e;
if (keyEvent.key === 'Enter' || keyEvent.key === ' ') {
keyEvent.preventDefault();
clickHandler();
}
});
});
}
// ==========================================================================
// CATEGORY TILE NAVIGATION
// ==========================================================================
function initCategoryTiles() {
const categoryTiles = document.querySelectorAll('.category-tile');
if (!categoryTiles.length)
return;
// Map category tiles to their corresponding sections
// Cradlepoint categories: WWAN Routers, Switches & APs, WWAN Adapters, Private 5G, Accessories
const categoryMapping = [
{ index: 0, section: 'wwan-routers', name: 'WWAN Routers' },
{ index: 1, section: 'switches-access-points', name: 'LAN Switches & Access Points' },
{ index: 2, section: 'wwan-adapters', name: 'WWAN Adapters' },
{ index: 3, section: 'private-5g', name: 'Private 5G / Neutral Host' },
{ index: 4, section: 'wwan-accessories', name: 'WWAN Accessories' }
];
categoryTiles.forEach((tile, index) => {
const htmlTile = tile;
// Add keyboard accessibility
htmlTile.setAttribute('role', 'button');
htmlTile.setAttribute('tabindex', '0');
const mapping = categoryMapping[index];
if (mapping) {
htmlTile.setAttribute('aria-label', `View ${mapping.name} products`);
}
// Add smooth hover transitions
if (!prefersReducedMotion) {
htmlTile.style.transition = `transform 0.3s ${EASING_SMOOTH}, box-shadow 0.3s ${EASING_SMOOTH}`;
}
const clickHandler = () => {
const tileMapping = categoryMapping[index];
if (tileMapping) {
const targetSection = document.querySelector(`[data-section="${tileMapping.section}"]`);
if (targetSection) {
smoothScrollTo(targetSection);
// Update active tab if exists
const correspondingTab = document.querySelector(`.brand-nav__tab[data-section="${tileMapping.section}"]`);
if (correspondingTab) {
const allTabs = document.querySelectorAll('.brand-nav__tab');
allTabs.forEach((t) => {
t.classList.remove('brand-nav__tab--active');
t.setAttribute('aria-selected', 'false');
});
correspondingTab.classList.add('brand-nav__tab--active');
correspondingTab.setAttribute('aria-selected', 'true');
}
}
}
};
htmlTile.addEventListener('click', clickHandler);
htmlTile.addEventListener('keydown', (e) => {
const keyEvent = e;
if (keyEvent.key === 'Enter' || keyEvent.key === ' ') {
keyEvent.preventDefault();
clickHandler();
}
});
});
}
// ==========================================================================
// MOBILE NAVIGATION SCROLL INDICATORS
// ==========================================================================
function initMobileNavScrollIndicators() {
const brandNav = document.querySelector('.brand-header__nav');
if (!brandNav)
return;
const navContainerMaybe = brandNav.querySelector('.brand-header__container');
if (!navContainerMaybe)
return;
const navContainer = navContainerMaybe;
// Create visual scroll indicators
const leftIndicator = document.createElement('div');
leftIndicator.className = 'nav-scroll-indicator nav-scroll-indicator--left';
leftIndicator.setAttribute('aria-hidden', 'true');
leftIndicator.style.cssText = `
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 40px;
background: linear-gradient(to right, rgba(255,255,255,0.95), transparent);
pointer-events: none;
opacity: 0;
transition: opacity 0.3s ease;
z-index: 2;
`;
const rightIndicator = document.createElement('div');
rightIndicator.className = 'nav-scroll-indicator nav-scroll-indicator--right';
rightIndicator.setAttribute('aria-hidden', 'true');
rightIndicator.style.cssText = `
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 40px;
background: linear-gradient(to left, rgba(255,255,255,0.95), transparent);
pointer-events: none;
opacity: 0;
transition: opacity 0.3s ease;
z-index: 2;
`;
brandNav.style.position = 'relative';
brandNav.appendChild(leftIndicator);
brandNav.appendChild(rightIndicator);
// Use rAF-based throttle for smooth indicator updates during scroll
const scrollThrottle = createThrottle();
function updateScrollIndicators() {
const isScrollable = navContainer.scrollWidth > navContainer.clientWidth;
const scrollLeft = navContainer.scrollLeft;
const maxScroll = navContainer.scrollWidth - navContainer.clientWidth;
if (isScrollable) {
// Show left indicator if scrolled right
leftIndicator.style.opacity = scrollLeft > 10 ? '1' : '0';
// Show right indicator if not at end
rightIndicator.style.opacity = scrollLeft < maxScroll - 10 ? '1' : '0';
}
else {
leftIndicator.style.opacity = '0';
rightIndicator.style.opacity = '0';
}
}
navContainer.addEventListener('scroll', () => {
scrollThrottle(updateScrollIndicators);
}, { passive: true });
window.addEventListener('resize', () => {
scrollThrottle(updateScrollIndicators);
}, { passive: true });
// Initial check -- call directly, no delay needed
requestAnimationFrame(updateScrollIndicators);
}
// ==========================================================================
// IMAGE ERROR HANDLING
// ==========================================================================
function initImageErrorHandling() {
const images = document.querySelectorAll('img');
images.forEach((img) => {
// Skip if already loaded
if (img.complete && img.naturalHeight !== 0)
return;
img.addEventListener('error', function () {
// Add error class for styling
this.classList.add('image-error');
this.alt = this.alt || 'Image failed to load';
// Set a minimal fallback background
this.style.backgroundColor = '#f0f0f0';
this.style.minHeight = '200px';
}, { once: true });
});
}
// ==========================================================================
// LAZY LOADING
// ==========================================================================
function initLazyLoading() {
// Add loading="lazy" to images below the fold
const images = document.querySelectorAll('img:not([loading])');
images.forEach((img, index) => {
// First 3 images are likely above fold (hero, story cards)
if (index > 3) {
img.setAttribute('loading', 'lazy');
}
});
}
// ==========================================================================
// CLEANUP
// ==========================================================================
function cleanup() {
// Clear testimonial interval
if (testimonialInterval) {
clearInterval(testimonialInterval);
}
// Disconnect all observers
observers.forEach((observer) => {
if (observer && typeof observer.disconnect === 'function') {
observer.disconnect();
}
});
}
// ==========================================================================
// GLOBAL BUTTON HOVER POLISH
// ==========================================================================
function initButtonHoverPolish() {
if (prefersReducedMotion)
return;
const buttons = document.querySelectorAll('button, .btn, .brand-nav__tab, .category-tile');
buttons.forEach((button) => {
const htmlButton = button;
// Skip if already has transition
const currentTransition = window.getComputedStyle(htmlButton).transition;
if (currentTransition && currentTransition !== 'none' && currentTransition !== 'all 0s ease 0s')
return;
// Only animate visual properties -- avoid 'all' which can cause layout jank
htmlButton.style.transition = `opacity 0.2s ${EASING_SMOOTH}, box-shadow 0.2s ${EASING_SMOOTH}, background-color 0.2s ${EASING_SMOOTH}, color 0.2s ${EASING_SMOOTH}, border-color 0.2s ${EASING_SMOOTH}`;
});
}
// ==========================================================================
// HERO VIDEO BACKGROUND -- Auto-playing looping video
// ==========================================================================
function initHeroVideo() {
const videoEl = document.querySelector('.hero__bg-video');
if (!videoEl)
return;
const video = videoEl;
// Deferred video loading: wait 3s or first user interaction, whichever comes first.
// Video has preload="none" so the poster image shows immediately without competing bandwidth.
function loadAndPlay() {
if (video.preload !== 'none')
return; // Already loaded
video.preload = 'auto';
video.load();
video.play().catch(() => {
// Autoplay blocked -- poster image shown as fallback
});
}
const timer = setTimeout(loadAndPlay, 3000);
const interactionEvents = ['scroll', 'mousemove', 'touchstart', 'keydown'];
function onInteraction() {
clearTimeout(timer);
interactionEvents.forEach((evt) => {
window.removeEventListener(evt, onInteraction);
});
loadAndPlay();
}
interactionEvents.forEach((evt) => {
window.addEventListener(evt, onInteraction, { once: true, passive: true });
});
}
// ==========================================================================
// COMPARISON TABLE -- Column hover highlighting + "See options" scroll targets
// ==========================================================================
function initComparisonTable() {
const table = document.querySelector('.comparison-table');
if (!table)
return;
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
if (!thead || !tbody)
return;
// --- Column hover highlighting ---
const allRows = table.querySelectorAll('tr');
// Add/remove highlight class on all cells in a column
function highlightColumn(colIndex, active) {
allRows.forEach(function (row) {
const cell = row.children[colIndex];
if (cell) {
if (active) {
cell.style.backgroundColor = 'rgba(0, 125, 195, 0.06)';
}
else {
cell.style.backgroundColor = '';
}
}
});
}
// Attach hover listeners to every cell (skip col 0 -- that's the label column)
allRows.forEach(function (row) {
Array.from(row.children).forEach(function (cell, colIndex) {
if (colIndex === 0)
return;
cell.addEventListener('mouseenter', function () {
highlightColumn(colIndex, true);
});
cell.addEventListener('mouseleave', function () {
highlightColumn(colIndex, false);
});
});
});
// --- Sticky thead within wrapper on scroll ---
const wrapper = document.querySelector('.comparison-table-wrapper');
if (wrapper && thead) {
const tableThrottle = createThrottle();
wrapper.addEventListener('scroll', function () {
tableThrottle(function () {
const scrollTop = wrapper.scrollTop;
if (scrollTop > 0) {
thead.style.position = 'sticky';
thead.style.top = '0';
thead.style.zIndex = '2';
}
});
}, { passive: true });
// Set sticky by default (works if wrapper has overflow-y)
thead.style.position = 'sticky';
thead.style.top = '0';
thead.style.zIndex = '2';
}
// --- "See options" buttons scroll to product sections ---
const lastRow = tbody.querySelector('tr:last-child');
if (!lastRow)
return;
const seeOptionsButtons = lastRow.querySelectorAll('.btn--amazon');
// Map each button to the section it should scroll to
// Cradlepoint comparison table columns map to WWAN Routers and WWAN Adapters sections
const scrollTargets = [
function () { return document.getElementById('wwan-routers'); },
function () { return document.getElementById('wwan-routers'); },
function () { return document.querySelector('.featured-products--adapters'); },
function () { return document.querySelector('.featured-products--adapters'); }
];
seeOptionsButtons.forEach(function (btn, index) {
if (!scrollTargets[index])
return;
btn.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation(); // Prevent cart counter from firing
const target = scrollTargets[index]();
if (target) {
smoothScrollTo(target);
}
});