summaryrefslogtreecommitdiff
path: root/js/parallax.js
blob: 9c2c671b90d3ff76ef5034fde890aff47ecfed53 (plain)
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
// Parallax scroll effects for Nixtaml website
// Vanilla JavaScript implementation with performance optimizations

(function() {
    // Check for reduced motion preference
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    // Check if mobile (disable parallax for better performance)
    const isMobile = window.innerWidth < 768;

    // If reduced motion or mobile, exit early
    if (prefersReducedMotion || isMobile) {
        return;
    }

    // Throttle function for scroll events
    function throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        }
    }

    // Parallax animation function
    let ticking = false;
    function updateParallax() {
        if (!ticking) {
            requestAnimationFrame(function() {
                const scrolled = window.pageYOffset;

                // Get all elements with data-speed
                const parallaxElements = document.querySelectorAll('[data-speed]');

                parallaxElements.forEach(element => {
                    const speed = parseFloat(element.getAttribute('data-speed')) || 0;
                    const yPos = -(scrolled * speed);
                    element.style.transform = `translateY(${yPos}px)`;
                });

                ticking = false;
            });
            ticking = true;
        }
    }

    // Throttled scroll handler
    const throttledUpdate = throttle(updateParallax, 16); // ~60fps

    // Add scroll listener
    window.addEventListener('scroll', throttledUpdate, { passive: true });

    // Initial call
    updateParallax();
})();</content>
<parameter name="filePath">js/parallax.js