Skip to content

Instantly share code, notes, and snippets.

@danieluhl
Last active December 20, 2016 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieluhl/2673bbcedfb1f648bfc6fe377884f006 to your computer and use it in GitHub Desktop.
Save danieluhl/2673bbcedfb1f648bfc6fe377884f006 to your computer and use it in GitHub Desktop.
const keyElements = document.querySelectorAll('.key');
const audioElements = document.querySelectorAll('audio');
const sounds = {};
const keys = {};
// got this from wes bos
function removeTransition (e) {
if (e.propertyName !== 'transform') return;
e.target.classList.remove('playing');
}
audioElements.forEach((el) => {
sounds[el.getAttribute('data-key')] = el;
});
const play = (key) => {
const keyElement = keys[key];
const sound = sounds[key];
sound.currentTime = 0;
keyElement.classList.add('playing');
const playPromise = sound.play();
};
// add listeners on keys and clicks
keyElements.forEach((key) => {
// got from wes bos
keys[el.getAttribute('data-key')] = el;
key.addEventListener('transitionend', removeTransition);
key.addEventListener('click', () => play(key.getAttribute('data-key')));
});
window.addEventListener('keyup', (key) => {
if (keys[key.keyCode]) {
play(key.keyCode);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment