Skip to content

Instantly share code, notes, and snippets.

@cupofjoey
Created December 11, 2016 20:19
Show Gist options
  • Save cupofjoey/020da4bbb8f8e4d87058113b64ec5fef to your computer and use it in GitHub Desktop.
Save cupofjoey/020da4bbb8f8e4d87058113b64ec5fef to your computer and use it in GitHub Desktop.
JS30 Day 1
script>
function removeTransition(e) {
if (e.propertyName !== 'transform') return;
e.target.classList.remove('playing');
}
function playSound(e) {
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
if (!audio) return;
key.classList.add('playing');
audio.currentTime = 0;
audio.play();
}
const keys = Array.from(document.querySelectorAll('.key'));
keys.forEach(key => key.addEventListener('transitionend', removeTransition));
window.addEventListener('keydown', playSound);
</script>
<script>
function playSound(e) {
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
if (!audio) return; // stop the function from running all together
audio.currentTime = 0; // rewind to the start
audio.play();
key.classList.add('playing');
}
function removeTransition(e) {
if (e.propertyName !== 'transform') return; // skip it if it's not a transform
this.classList.remove('playing');
}
const keys = document.querySelectorAll('.key');
keys.forEach(key => key.addEventListener('transitionend', removeTransition));
window.addEventListener('keydown', playSound);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment