Reputation: 844
WHAT I WANT TO DO
I want to shorten my code. This Drum Play App plays sound by pressing certain keys or clicking with your mouse.
It works, but the code for click events is too long because I repeated the same code many times.
Could anyone make it cleaner/shorter?
WHAT I TRIED
I tried for loop, like below:
document.querySelector(`div[data-key="${dataKeys[i]}"]`).addEventListener...
But it didn't work.
MY CURRENT CODE
Here is my code.
<body>
<div class="keys">
<div data-key="65" class="key">
<kbd>A</kbd>
<span class="sound">clap</span>
</div>
<div data-key="83" class="key">
<kbd>S</kbd>
<span class="sound">hihat</span>
</div>
<div data-key="68" class="key">
<kbd>D</kbd>
<span class="sound">kick</span>
</div>
...
</div>
<audio data-key="65" src="sounds/clap.wav"></audio>
<audio data-key="83" src="sounds/hihat.wav"></audio>
<audio data-key="68" src="sounds/kick.wav"></audio>
...
<script>
window.addEventListener('keydown', function(e) {
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
if (!audio) return; // Stop the function from running all together
audio.currentTime = 0; // Rewind to the start
audio.play();
});
document.querySelector('div[data-key="65"]').addEventListener('click', function(e) {
console.log('I clicked.')
const clickedAudio = document.querySelector(`audio[data-key="65"]`);
clickedAudio.currentTime = 0; // Rewind to the start
clickedAudio.play();
});
document.querySelector('div[data-key="83"]').addEventListener('click', function(e) {
console.log('I clicked.')
const clickedAudio = document.querySelector(`audio[data-key="83"]`);
clickedAudio.currentTime = 0; // Rewind to the start
clickedAudio.play();
});
document.querySelector('div[data-key="68"]').addEventListener('click', function(e) {
console.log('I clicked.')
const clickedAudio = document.querySelector(`audio[data-key="68"]`);
clickedAudio.currentTime = 0; // Rewind to the start
clickedAudio.play();
});
...
</script>
</body>
I'd appreciate it if anyone could make my code cleaner or shorter.
Upvotes: 2
Views: 128
Reputation: 370859
Select all .key
elements, check their dataset to get their associated key number, and then you can dynamically select the associated audio
:
document.querySelectorAll('.key').forEach((div) => {
div.addEventListener('click', () => {
const { key } = div.dataset;
const clickedAudio = document.querySelector(`audio[data-key="${key}"]`);
clickedAudio.currentTime = 0; // Rewind to the start
clickedAudio.play();
});
});
Upvotes: 6