1
+ let videoHero = function ( ) {
2
+ /* My refactored code */
3
+ var heroVid = document . querySelector ( '[data-video="hero"]' ) ;
4
+ var heroVidControl = document . querySelector ( '[data-video-control="hero"]' ) ;
5
+
6
+ if ( heroVid && heroVidControl ) {
7
+ // Remove native controls and show custom button
8
+ heroVid . removeAttribute ( "controls" ) ;
9
+ heroVidControl . removeAttribute ( "hidden" ) ;
10
+
11
+ // Media query for reduced motion preference
12
+ var motionQuery = window . matchMedia ( "(prefers-reduced-motion)" ) ;
13
+
14
+ // Helper to update button text
15
+ function updateButtonState ( isPlaying ) {
16
+ const label = isPlaying ? heroVidControl . dataset . videoPause : heroVidControl . dataset . videoPlay ;
17
+ heroVidControl . querySelector ( "span" ) . innerText = label ;
18
+ heroVidControl . classList . toggle ( "js-play-video" , isPlaying ) ;
19
+ }
20
+
21
+ // Play video with error handling
22
+ function playHeroVid ( ) {
23
+ heroVid . play ( ) . then ( ( ) => {
24
+ updateButtonState ( true ) ;
25
+ } ) . catch ( ( error ) => {
26
+ console . warn ( "Video play failed:" , error ) ;
27
+ updateButtonState ( false ) ;
28
+ } ) ;
29
+ }
30
+
31
+ // Pause video
32
+ function pauseHeroVid ( ) {
33
+ heroVid . pause ( ) ;
34
+ updateButtonState ( false ) ;
35
+ }
36
+
37
+ // Handle user motion preference
38
+ function handleReduceMotionChanged ( ) {
39
+ if ( motionQuery . matches ) {
40
+ pauseHeroVid ( ) ;
41
+ } else {
42
+ playHeroVid ( ) ;
43
+ }
44
+ }
45
+
46
+ // Attempt to autoplay
47
+ var promise = heroVid . play ( ) ;
48
+ if ( promise !== undefined ) {
49
+ promise
50
+ . then ( ( ) => {
51
+ updateButtonState ( true ) ;
52
+ } )
53
+ . catch ( ( error ) => {
54
+ console . warn ( "Autoplay was prevented:" , error ) ;
55
+ updateButtonState ( false ) ;
56
+ } ) ;
57
+ }
58
+
59
+ // Media query listener
60
+ motionQuery . addEventListener ( "change" , handleReduceMotionChanged ) ;
61
+ handleReduceMotionChanged ( ) ;
62
+
63
+ // Toggle video playback on control click
64
+ document . addEventListener ( "click" , function ( event ) {
65
+ const button = event . target . closest ( '[data-video-control="hero"]' ) ;
66
+ if ( button ) {
67
+ if ( heroVid . paused ) {
68
+ playHeroVid ( ) ;
69
+ } else {
70
+ pauseHeroVid ( ) ;
71
+ }
72
+ }
73
+ } ) ;
74
+
75
+ // Unregister media query listener on page unload to prevent memory leaks
76
+ window . addEventListener ( "beforeunload" , ( ) => {
77
+ motionQuery . removeEventListener ( "change" , handleReduceMotionChanged ) ;
78
+ } ) ;
79
+ }
80
+ }
81
+ export { videoHero }
0 commit comments