본문 바로가기
Web Dev

Advanced Javascript and DOM Manipulation - Drum kit

by YGSEO 2021. 1. 6.
728x90

addEventListener()

The EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).

 

addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the specified event type on the EventTarget on which it's called.

 

target.addEventListener(type, listener [, options]);
target.addEventListener(type, listener [, useCapture]);
target.addEventListener(type, listener [, useCapture, wantsUntrusted ]); // Gecko/Mozilla only

What are "type, listener" in addEventListener() ?

type

    A case-sensitive string representing the event type to listen for.

listener

    The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or a JavaScript function. See The event listener callback for details on the callback itself.

 

// add eventlistener to button so that it listens for "click" event.
// Then, as it listened for "click" that happens on that button, it runs the code, i.e. handlleclick function.

document.querySelector("button").addEventListener("click", handleClick);

function handleClick() {
    alert("I got clicked");
}

**event type: link

ex.


In this code below, why calling function without parenthesis?

// add eventlistener to button so that it listens for "click" event.
// Then, as it listened for "click" that happens on that button, it runs the code, i.e. handlleclick function.

document.querySelector("button").addEventListener("click", handleClick);

function handleClick() {
    alert("I got clicked");
}

If we put the parenthesis, it means we straightly call the function right away, not waiting a "click" event.

Thus, instead of calling function with parenthesis, passing it just the name of the function.

 

Instead of adding a function name that calls the function, the most common way is writing an anonymous function.

What an anonymous function is the function without a name.

// add eventlistener to button so that it listens for "click" event.
// Then, as it listened for "click" that happens on that button, it runs the code, i.e. handlleclick function.

document.querySelector("button").addEventListener("click", function () {
    alert("I got clicked");
});

But as I implement the code above, it only happens once not for all the buttons in the html.

How to implement all the buttons?

If I find all the buttons by using "querySelectorALL", it returns a list of buttons.

This means that I have to apply "addEventListener" to all the buttons I have.

 

A better way to do this is using a for loop.

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

for (var i = 0; i < numOfDrumButtons; i++) {
    document.querySelectorAll(".drum")[i].addEventListener("click", function () {
        alert("I got clicked");
    });
}

Add audio element

var audio = new Audio('sounds/tom-1.mp3');
audio.play();

'this' in JS

im-developer.tistory.com/96

 

[JS/this] 자바스크립트, this의 4가지 역할

Javascript, This. 자바스크립트에는 this라는 키워드가 있다. this는 문맥에 따라서 다양한 값을 가지는 데, this가 쓰이는 함수를 어떤 방식으로 실행하느냐에 따라서 그 역할이 구별된다. this의 값들

im-developer.tistory.com

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this

 

this - JavaScript | MDN

JavaScript에서 함수의 this 키워드는 다른 언어와 조금 다르게 동작합니다. 또한 엄격 모드와 비엄격 모드에서도 일부 차이가 있습니다. 대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결

developer.mozilla.org


A Deeper Understanding of JS Objects


Switch Statement

switch (buttonInnerHTML) {
            case 'w':
                var tom1 = new Audio("sounds/tom-1.mp3");
                tom1.play();
                break;

            default:
        }

Methods

A method is just a function that associated with an object.

var bellBoy1 = {
    name: "Timmy",
    age: 19,
    hasWorkPermit: true,
    language: ["French", "English"],
    moveSuitcase: function() {
        alert("May I take your suitcase?");
        pickUpSuitcase();
        move();
    }
}

bellBoy1 has a method of moveSuitcase.


Call Method

bellBoy1.moveSuitcase();
function BellBoy (name, age, hasWorkPermit, languages) {
    this.name = name;
    this.age = age;
    this.hasWorkPermit = hasWorkPermit;
    this.languages = languages;
    this.moveSuitcase = function() {
        alert("May I take your suitcase?");
        pickUpSuitcase();
        move();;
    }
}

Keyboard events

// add eventlistener to button so that it listens for "click" event.
// Then, as it listened for "click" that happens on that button, it runs the code, i.e. handlleclick function.

// Detecting Button Press
var numOfDrumButtons = document.querySelectorAll(".drum").length;

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

        var buttonInnerHTML = this.innerHTML;

        makeSound(buttonInnerHTML);

    });
}

// Detecting Keyboard Press
//  add Eventlistener to entire web page.
document.addEventListener("keydown", function(event) {
    makeSound(event.key)
    })

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 snare = new Audio('sounds/snare.mp3');
          snare.play();
          break;
    
        case "k":
          var crash = new Audio('sounds/crash.mp3');
          crash.play();
          break;
    
        case "l":
          var kick = new Audio('sounds/kick-bass.mp3');
          kick.play();
          break;
    
        default: console.log(key);
    }
}

Callbacks

1.callback이란?

javascript에서는 callback 함수는 다른 함수의 매개변수로 함수를 전달하고, 어떠한 이벤트가 발생한 후 매개변수로 전달한 함수가 다시 호출되는 것을 의미합니다.

callback은 쉽게 말하자면 어떤 일을 다른 객체에게 시키고, 그 일이 끝나는 것은 기다리지 않고 끝나고 부를 때까지 다른 일을 하는 것을 말합니다.

그렇기 때문에 non-block이며, 비동기 방식의 함수를 사용합니다.

 

www.zerocho.com/category/JavaScript/post/57432d2aa48729787807c3fc

 

(JavaScript) 이벤트 리스너와 콜백(event listener, callback)

안녕하세요. 이번 시간은 이벤트 리스너와 콜백 차례입니다. 지금까지는 이벤트 리스너를 안 다뤘습니다만 이제 다룰 때가 된 것 같습니다. 이벤트 리스너와 콜백 방식도 자바스크립트에서 많

www.zerocho.com

hees-dev.tistory.com/33

 

[Javascript] callback(콜백) 개념 이해하기

Javascript로 개발을 하신다면 'callback'이라는 키워드를 한 번쯤 들어보셨을 것이라 생각합니다. 과연 callback이란 무엇일까요? 1.callback이란? javascript에서는 callback 함수는 다른 함수의 매개변수로 함

hees-dev.tistory.com


Adding Animation to Websites

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

        var buttonInnerHTML = this.innerHTML;

        makeSound(buttonInnerHTML);

        buttonAnimation(buttonInnerHTML);

    });
}

// Detecting Keyboard Press
//  add Eventlistener to entire web page.
document.addEventListener("keydown", function(event) {
    makeSound(event.key)
    buttonAnimation(event.key)
    })


function buttonAnimation(currentKey){

    var activeButton = document.querySelector("."+currentKey) //found the button

    activeButton.classList.add("pressed")

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

}

 

 

developer.mozilla.org/ko/docs/Web/API/WindowTimers/setTimeout

 

WindowTimers.setTimeout() - Web API | MDN

WindowTimers.setTimeout() Jump to sectionJump to section 타이머가 만료된 뒤 함수나 지정된 코드를 실행하는 타이머를 설정합니다.var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]); var timeoutID = window.setTim

developer.mozilla.org

 

728x90

댓글