Home > Enterprise >  How to out JQuery buttons and key presses for sound and animation
How to out JQuery buttons and key presses for sound and animation

Time:09-23

I want to replace the Vanilla JavaScript code with the JQuery. Here whenever I click a button on the webpage, it is supposed to play the animation and play the sound. Also, when I press a suitable key, e.g. "w", it is also supposed to play that respective sound. However, I am not sure why it is not working and if it is even possible.

JavaScript

var numberOfDrumButtons = document.querySelectorAll(".drum").length;

$("button").on("click", function(){
  makeSound(event.key);
  buttonAnimation(event.key);
});
$(document).keydown(function(event) {
  makeSound(event.key);
  buttonAnimation(event.key);
});


function makeSound(key) {
  switch (key) {
    case "w":
      var audio1 = new Audio("sounds/crash.mp3");
      audio1.play();
      break;
    case "a":
      var audio2 = new Audio("sounds/kick-bass.mp3");
      audio2.play();
      break;
    case "s":
      var audio3 = new Audio("sounds/snare.mp3");
      audio3.play();
      break;
    case "d":
      var audio4 = new Audio("sounds/tom-1.mp3");
      audio4.play();
      break;
    case "j":
      var audio5 = new Audio("sounds/tom-2.mp3");
      audio5.play();
      break;
    case "k":
      var audio6 = new Audio("sounds/tom-3.mp3");
      audio6.play();
      break;
    case "l":
      var audio7 = new Audio("sounds/tom-4.mp3");
      audio7.play();
      break;
    default: console.log()
  }

}

function buttonAnimation(currentKey) {
  var activeButton = document.querySelector("."   currentKey);

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

HTML

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Drum Kit</title>
  <link rel="stylesheet" href="styles.css">
  <link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
</head>

<body>
  <h1 id="title">Drum            
  • Related