Events in JavaScript

Events in JavaScript

Introduction

  • So, now we know what a DOM is can manipulate it yay!

  • But so far we didnt do what most users do a lot of clicking and mashing the keyboard.

  • So how do we do things when the user does some action?

  • how do we let the program know?

  • TLDR, we use action listeners.

addActionListener()

  • we can use the addActionListener() method on any element in the DOM including the document to make it listen to an event.

  • The event to be listened to in given as the first parameter, and what it does is given usually as an anonymous function as the second parameter.

document.querySelector("button").addActionListener("click",function(){
alert("button clicked");
});
  • Now lets try to learn more about this using a simple project.

What project?

  • We are going to make a drumkit in the web.

  • This drumkit will make the corresponding sound when clicked on or we press the key on the keyboard.

Adding the listener

  • We need our program to listen to 2 things, keyboard and mouse.

  • lets focus on the mouse first.

  • We have to add the listener to each button play the corresponding sound.

  • we can do this by adding actionlistener to each button individually or use a loop cus we lazy like that.

for (var i=0;i<buttons.length; i++ ){
    document.querySelectorAll(".button")[i].addEventListener("click", function(){

    });
}
  • We use querySelectorAll to get all the buttons and then let it run through a loop and add evenListeners for click with a function.

  • I could type out the whole function here, but since we'll need the same function for keyboard events we'll make that a separate function and call that here

for (var i=0;i<buttons.length; i++ ){
    document.querySelectorAll(".button")[i].addEventListener("click", function(){
        playAudio(this.innerHTML);
        buttonAnimation(this.innerHTML);
    });
}
  • Here I have two functions one for the sound and one for that flicker.

  • They take the parameter this.innerHTML.

  • 'this' gives back the element that got clicked, we then retrieve its innerHTML to get the letter which is passed into both functions.

  • Time for the keyboard actions.

  • the mouse event we listened to the buttons but what do we listen to for the keyboard events?

  • The answer is the whole document, we add the eventListener to the entire document add the same two functions as for the mouse events

document.addEventListener("keydown",function(event){
    playAudio(event.key);
    buttonAnimation(event.key);
});
  • Here the parameter is event.key

  • You may have noticed that out anonymous function has an extra parameter event that represents the event that occured, in this case which key was pressed.

  • The event is an object with a lot of properties including which key was pressed which we give into the function.

PlayAudio

function playAudio(key){
    switch (key){
        case "w" :
            var audio=new Audio("./resources/sounds/crash.mp3");
            break;
        case "a" :
            var audio=new Audio("./resources/sounds/kick-bass.mp3");
            break;
        case "s" :
            var audio=new Audio("./resources/sounds/snare.mp3");
            break;
        case "d" :
            var audio=new Audio("./resources/sounds/tom-1.mp3");
            break;
        case "j" :
            var audio=new Audio("./resources/sounds/tom-2.mp3");
            break;
        case "k" :
            var audio=new Audio("./resources/sounds/tom-3.mp3");
            break;
        case "l" :
            var audio=new Audio("./resources/sounds/tom-4.mp3");
            break;
        default:
            console.log(this.innerHTML);
    }
    audio.play();
}
  • We take the parameter given (which button was clicked) and depending on which button it was we create and audio object.

  • we then play it at the end of the switch case.

  • This does have the problem of giving us an error when we press a button other that those we gave because it would try to play without creating an object.

buttonAnimation

function buttonAnimation(key){
    document.querySelector("."+key).classList.add("pressed");
    setTimeout( function(){
        document.querySelector("."+key).classList.remove("pressed")},
        100
    );
}
  • In the button animation function we simply add the class pressed to the button being pressed and then after 0.1 seconds remove it by using the setTimeout function.

  • Which takes in the function to be done and the time after which it should be executed.

Conclusion

  • We ended up learning about event listeners and how to play audio using javascript here.

  • What will be next lets see haha

github -> https://github.com/P-M-Manmohan

LinkedIn -> https://www.linkedin.com/in/manmohan-p-m-78618323a/

Did you find this article valuable?

Support The Journey by becoming a sponsor. Any amount is appreciated!