|
59 | 59 |
|
60 | 60 | <script> |
61 | 61 |
|
| 62 | +function playSound(e) { |
| 63 | + const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`); |
| 64 | + const key = document.querySelector(`.key[data-key="${e.keyCode}"]`); |
| 65 | + // const is new in ECMAScript 6; it allows assignment of a variable that won't be reassigned |
| 66 | + //${} is notation for an ES 6 template string; in earlier ES versions, this would be ("audio[data-key=\"" + e.keyCode + "\"]") |
| 67 | + if (!audio) return; //stop the function from running if no audio element containing the keyCode of the pressed key as a data-key attribute is present |
| 68 | + audio.currentTime=0; //rewind to start, allows pressing key in rapid succession |
| 69 | + audio.play(); |
| 70 | + key.classList.add('playing'); |
| 71 | +}; |
62 | 72 |
|
63 | | - function playSound(e) { |
64 | | - const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`); |
65 | | - const key = document.querySelector(`.key[data-key="${e.keyCode}"]`); |
66 | | - if (!audio) return; // stop the function from running all together |
67 | | - audio.currentTime = 0; // rewind to the start |
68 | | - audio.play(); |
69 | | - key.classList.add('playing'); |
70 | | - } |
71 | | - function removeTransition(e) { |
72 | | - if (e.propertyName !== 'transform') return; // skip it if it's not a transform |
73 | | - this.classList.remove('playing'); |
74 | | - } |
| 73 | +function removeTransition(e) { |
| 74 | + if(e.propertyName !== 'transform') return; //skip if it's not a transform, because many different css properties are transitioning and you only need the eventListener to look at one |
| 75 | + this.classList.remove('playing'); |
| 76 | +} |
75 | 77 |
|
76 | | - const keys = document.querySelectorAll('.key'); |
77 | | - keys.forEach(key => key.addEventListener('transitionend', removeTransition)); |
78 | | - window.addEventListener('keydown', playSound); |
| 78 | +const keys = document.querySelectorAll('.key'); |
| 79 | +keys.forEach (key => key.addEventListener('transitionend', removeTransition)); |
| 80 | +/*Arrow functions are also new in ES6. In the above example, it provides a concise way of expressing a function. |
| 81 | +The arguments used in the function are listed before the arrow, the expression after the arrow is the function. |
| 82 | +The old way would be writing: |
| 83 | +keys.forEach(function(key) { |
| 84 | + return key.AddEventListener('transitionend', removeTransition); |
| 85 | +});*/ |
| 86 | +window.addEventListener('keydown', playSound); |
79 | 87 |
|
80 | 88 | </script> |
81 | 89 |
|
|
0 commit comments