File tree Expand file tree Collapse file tree 1 file changed +15
-26
lines changed Expand file tree Collapse file tree 1 file changed +15
-26
lines changed Original file line number Diff line number Diff line change 59
59
60
60
< script >
61
61
62
- const keys = document . querySelectorAll ( '.key' )
63
- const audio = document . querySelectorAll ( 'audio' )
64
-
62
+
65
63
const playSoundAndAnimateKey = ( e ) => {
66
- const keyname = e . key
67
- keys . forEach ( ( key ) => {
68
- if ( key . children [ 0 ] . textContent . toLowerCase ( ) === keyname ) {
69
- audio . forEach ( ( sound ) => {
70
- if ( sound . dataset . key === key . dataset . key ) {
71
- sound . currentTime = 0 ;
72
- sound . play ( )
73
- key . classList . toggle ( 'playing' )
74
- }
75
- } )
76
- }
77
- } )
64
+ const key = document . querySelector ( `div[data-key="${ e . keyCode } "]` )
65
+ const audio = document . querySelector ( `audio[data-key="${ e . keyCode } "]` )
66
+ if ( ! audio ) {
67
+ return
68
+ }
69
+ audio . currentTime = 0 ;
70
+ audio . play ( )
71
+ key . classList . toggle ( 'playing' )
78
72
}
79
73
80
74
const stopAnimationKey = ( e ) => {
81
- const keyname = e . key
82
- keys . forEach ( ( key ) => {
83
- if ( key . children [ 0 ] . textContent . toLowerCase ( ) === keyname ) {
84
- audio . forEach ( ( sound ) => {
85
- if ( sound . dataset . key === key . dataset . key ) {
86
- key . classList . toggle ( 'playing' )
87
- }
88
- } )
89
- }
90
- } )
75
+ const key = document . querySelector ( `div[data-key="${ e . keyCode } "]` )
76
+ if ( ! key ) {
77
+ return
78
+ }
79
+ key . classList . toggle ( 'playing' )
91
80
}
92
81
93
- document . addEventListener ( 'keypress ' , playSoundAndAnimateKey , false )
82
+ document . addEventListener ( 'keydown ' , playSoundAndAnimateKey , false )
94
83
document . addEventListener ( 'keyup' , stopAnimationKey , false )
95
84
96
85
</ script >
You can’t perform that action at this time.
0 commit comments