|
4 | 4 | <meta charset="UTF-8" /> |
5 | 5 | <title>JS Drum Kit</title> |
6 | 6 | <link rel="stylesheet" href="style.css" /> |
7 | | - <link rel="icon" href="https://fav.farm/🔥" /> |
| 7 | + <link rel="icon" href="https://fav.farm/✅" /> |
8 | 8 | </head> |
9 | 9 | <body> |
10 | 10 | <div class="keys"> |
|
57 | 57 | <audio data-key="76" src="sounds/tink.wav"></audio> |
58 | 58 |
|
59 | 59 | <script> |
60 | | - document.addEventListener("keydown", (evt) => { |
61 | | - const audio = document.querySelector( |
62 | | - `audio[data-key="${evt.keyCode}"]` |
63 | | - ); |
64 | | - const key = document.querySelector(`.key[data-key="${evt.keyCode}"]`); |
65 | | - if (!audio) return; |
66 | | - key.classList.add("playing"); |
| 60 | + function removeTransition(e) { |
| 61 | + if (e.propertyName !== "transform") return; |
| 62 | + e.target.classList.remove("playing"); |
| 63 | + } |
| 64 | + |
| 65 | + function playSound(e) { |
| 66 | + const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`); |
| 67 | + const key = document.querySelector(`div[data-key="${e.keyCode}"]`); |
| 68 | + if (!audio) return; //stop the function from running when hitting a non available option |
| 69 | + |
| 70 | + key.classList.add("playing"); //same as key.addClass in JQuery |
| 71 | + |
| 72 | + /*Ensures that the sound always plays from the beginning. Otherwise, |
| 73 | + if the 'a' key is pressed twice rapidly, the soundclip will only play through |
| 74 | + once*/ |
67 | 75 | audio.currentTime = 0; |
68 | | - audio.play(); |
69 | | - }); |
| 76 | + audio.play(); // Play sound |
| 77 | + } |
70 | 78 |
|
71 | | - const keys = document.querySelectorAll(".key"); |
| 79 | + const keys = Array.from(document.querySelectorAll(".key")); // Find all elements in the document with a class 'key' |
| 80 | + // Listen for any `keydown` events that occur on this browser window instance (this page) |
| 81 | + // When a `keydown` event is observered, trigger the `playSound` function, passing in the |
| 82 | + // `keydown` event as the argument (e) |
| 83 | + window.addEventListener("keydown", playSound); |
72 | 84 | keys.forEach((key) => |
73 | 85 | key.addEventListener("transitionend", removeTransition) |
74 | 86 | ); |
75 | | - |
76 | | - function removeTransition(evt) { |
77 | | - if (evt.propertyName == "transform") { |
78 | | - this.classList.remove("playing"); |
79 | | - } else return; |
80 | | - } |
81 | 87 | </script> |
82 | 88 | </body> |
83 | 89 | </html> |
0 commit comments