This is a JavaScript practice with JavaScript30 by Wes Bos without any frameworks, no compilers, no boilerplate, and no libraries.
key event listener, audio play and toggle class.
view demo here
window.addEventListener('keydown', playSound)
playSound()
is a listener forkeydown
events registered usingwindow.addEventListener
.window
is the global object in a browser, or the root object of the DOM. Anddocument
stands for DOM.
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
keyCode
property is the KEY to connect our buttons(<div>
s) and sounds(<audio>
s).keyCode
's value is same asASCII
code (in lowercase letter ), check keycodes here.data-key
is set for mapping buttons and audios to get thekeyCode
s viakeydown
event.- the whole
querySelector
expression has to be in back ticks (```). ${}
is syntactic sugar for template literals, read more aboutExpression interpolation
here
How do we prevent delay playing sound, if we keep hitting a key?
just add audio.currentTime = 0;
before audio.play();
-
use
item.classList.add('className')
to add class when key pressed. (same aselement.addClass('className')
in jQuery) -
use
transitionend
event to removeplay
class. since we want to just removetransform
property, so add a condition to skip others.
if(e.propertyName != 'transform') return;
this.classList.remove('playing'); // `event.target.classList.remove('playing');`
-
items.forEach()
instead of justforEach
, which means it's a property of an array. -
Arrow functions is ES6 syntax,
keys.forEach(key => key.addEventListener());