something in HTML
...
<div class="set">
<button class="w drum">w</button>
<button class="a drum">a</button>
<button class="s drum">s</button>
<button class="d drum">d</button>
<button class="j drum">j</button>
<button class="k drum">k</button>
<button class="l drum">l</button>
</div>
...
index.js - 01. Listen to keyboard
- Higher-order function :
addEventListener()
- Callback function :
function(key)
- 得到的回傳值key如下 :
> KeyboardEvent {isTrusted: true, key: 'd', code: 'KeyD', location: 0, ctrlKey: false, …}
key.key
==key["key"]
document.addEventListener("keydown", function(key) {
makeSound(key["key"]);
buttonAnimation(key["key"]);
})
index.js - 02. Listen to mouse
- 使用for迴圈讓每個button都可以listen
- 從被點擊的button回傳
this.innerHTML
var buttons = document.querySelectorAll(".drum")
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
var buttonInnerHTML = this.innerHTML;
makeSound(buttonInnerHTML);
buttonAnimation(buttonInnerHTML);
})
}
index.js - 03. Make sound function
- 建立音檔連結:
var audio = new Audio("URL")
- 以JS播放音檔:
audio.play()
function makeSound(key) {
switch (key) {
case "w":
var tom1 = new Audio("sounds/tom-1.mp3");
tom1.play();
break;
case "a":
var tom2 = new Audio("sounds/tom-2.mp3");
tom2.play();
break;
case "s":
var tom3 = new Audio("sounds/tom-3.mp3");
tom3.play();
break;
case "d":
var tom4 = new Audio("sounds/tom-4.mp3");
tom4.play();
break;
case "j":
var crash = new Audio("sounds/crash.mp3");
crash.play();
break;
case "k":
var kick = new Audio("sounds/kick-bass.mp3");
kick.play();
break;
case "l":
var snare = new Audio("sounds/snare.mp3");
snare.play();
break;
default: console.log(key);
}
}
index.js - 04. Button animation function
- 時間暫停fuction:
setTimeout(function, ms)
- 增加class:
item.classList.add("className");
- 刪去class:
item.classList.remove("className");
- 開關class:
item.classList.toggle("className");
function buttonAnimation(currentKey){
var activeButton = document.querySelector("." + currentKey);
activeButton.classList.add("pressed");
setTimeout(function(){
activeButton.classList.remove("pressed");
}, 100);
}