Last active
December 20, 2016 14:05
-
-
Save danieluhl/2673bbcedfb1f648bfc6fe377884f006 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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