File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 58
58
< audio data-key ="76 " src ="sounds/tink.wav "> </ audio >
59
59
60
60
< script >
61
+ const findSound = key => document . querySelector ( `audio[data-key="${ key } "]` ) ;
62
+ const findButton = key => document . querySelector ( `.keys [data-key="${ key } "]` ) ;
63
+ const findKeyRoot = leaf => leaf . closest ( `[data-key]` ) ;
64
+ const keyContainer = document . querySelector ( ".keys" ) ;
61
65
66
+ const playSound = ( audio , onStart , onStop ) => {
67
+ audio . onplaying = onStart ;
68
+ audio . onended = onStop ;
69
+ audio . play ( ) ;
70
+ } ;
71
+
72
+ const handlePlaying = ( el , sound ) => {
73
+ const onPlaying = ( ) => el . classList . add ( "playing" ) ;
74
+ const onEnded = ( ) => el . classList . remove ( "playing" ) ;
75
+ playSound ( sound , onPlaying , onEnded ) ;
76
+ } ;
77
+
78
+ document . addEventListener ( "keydown" , ( { keyCode } ) => {
79
+ const el = findButton ( keyCode ) ;
80
+ if ( ! el ) return ;
81
+ const sound = findSound ( keyCode ) ;
82
+ handlePlaying ( el , sound ) ;
83
+ } ) ;
84
+
85
+ keyContainer . addEventListener ( "click" , ( { target } ) => {
86
+ const el = findKeyRoot ( target ) ;
87
+ if ( ! el ) return ;
88
+ const key = el . dataset . key ;
89
+ const sound = findSound ( key ) ;
90
+ handlePlaying ( el , sound ) ;
91
+ } ) ;
62
92
</ script >
63
93
64
94
You can’t perform that action at this time.
0 commit comments