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
developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this
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
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
'Web Dev' 카테고리의 다른 글
Dicee (0) | 2021.01.05 |
---|---|
The Document Object Model (DOM) (0) | 2021.01.03 |
Intermediate Javascript (0) | 2021.01.02 |
Intermediate CSS - PART III (Refactoring II, Selector Priority) (0) | 2020.12.27 |
Intermediate CSS - PART II (Media Query Breakpoints, Refactoring, Selectors) (0) | 2020.12.26 |
댓글