JS Project - Drum Kit


Posted by pei_______ on 2022-05-30

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

  1. Higher-order function : addEventListener()
  2. Callback function : function(key)
  3. 得到的回傳值key如下 :
    > KeyboardEvent {isTrusted: true, key: 'd', code: 'KeyD', location: 0, ctrlKey: false, …}
  4. key.key == key["key"]
document.addEventListener("keydown", function(key) {
  makeSound(key["key"]);
  buttonAnimation(key["key"]);
})

index.js - 02. Listen to mouse

  1. 使用for迴圈讓每個button都可以listen
  2. 從被點擊的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

  1. 建立音檔連結: var audio = new Audio("URL")
  2. 以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

  1. 時間暫停fuction: setTimeout(function, ms)
  2. 增加class: item.classList.add("className");
  3. 刪去class: item.classList.remove("className");
  4. 開關class: item.classList.toggle("className");
function buttonAnimation(currentKey){

  var activeButton = document.querySelector("." + currentKey);

  activeButton.classList.add("pressed");

  setTimeout(function(){
    activeButton.classList.remove("pressed");
  }, 100);

}

#javascript #web系列







Related Posts

Vue、MVVM、MVC、雙向綁定

Vue、MVVM、MVC、雙向綁定

[筆記]ASIC Flow 01-ASIC是什麼?

[筆記]ASIC Flow 01-ASIC是什麼?

從 Closure 更深入理解 JavaScript 底層運作機制

從 Closure 更深入理解 JavaScript 底層運作機制


Comments