#JS 30 Play the piano… lesson #1
I’ve challenged myself with my work buddy that in 30 days we will finish course #JavaScript30, which teaches us pure vanilla JS and css/html things. I need it refresh my knowledge and unscramble it ;). So yesterday I took first lesson, which was creating some audio playing site while pressing some keys on keyboard.
All lessons will be available on https://github.com/rafath/js30 and code for first lesson is here: https://github.com/rafath/js30/tree/master/1
So… What I’ve learned today/yesterday:
For first time I used `<audio data-key=„65„ src=„sounds/a1.wav„></audio>` to play any sound, data-key – is attribute, which is read by function, to recognize for which key play which sound… in JS, you can use querySelector(selectorName)
, to find any selector with any attribute – for this you can use back-ticks: „ then `audio[data-key=”${e.keyCode}”]` which will be translated to `audio[data-key=”65″]` so JS will execute e.keyCode to its proper value.
Next thing is that you can add, remove, toggle anything to classList
of any element, so code like this: `this.classList.add(’someClass)` will add 'someClass' to tle class attribute. Simple.
The biggest surprise come with `addEventListener` in lesson we used some transition do animate keypressed key… and you have event for that… `transitionend` so you can write:
`key.addEventListener('transitionend', removeTransition)` the bolded function – is without parentheses (and to thie function, we are sending event as argument:
function removeTransition(e) { if (e.propertyName !== 'transform') return; this.classList.remove('playing'); }
So one more surprise is for yesterdays lesson was…
`audio.currentTime = 0` – which means that sound will always play after hitting the key so you have something like this:
audio.currentTime = 0; audio.play();
and audio is my audio element which I assigned here:
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
OK so enough for now – hopefully will learn next lesson today 😉 stay tuned Rafath ;))
Najnowsze komentarze