JS
JS - Vanilla JS Clone Project [Event Handlers]
Kai1996
2021. 12. 2. 12:08
이벤트 핸들러는 예제로 설명할예정이다.
//아래 두개의 선택자는 같은결과를 줌
const title = document.getElementById("title");
const title2 = document.querySelector("div .title");
console.log(title.innerText);
console.log(title2.innerText);
//Event handler
function handleTitleEnter(){
console.log("Title was clicked!");
title2.style.color = "Green";
title2.innerText = "KAI KIM";
}
function handleTitleLeave(){
console.log("Title was clicked!");
title2.style.color = "Black";
title2.innerText = "Grab Me!";
}
function handleWindowResize (){
document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy (){
alert("copier!");
}
function handleWindowOnline(){
title2.innerText += "User online";
}
function handleWindowOffline(){
title2.innerText += "User offline";
}
//Call the event upon the user's behavior
// title2.addEventListener("mouseenter" , handleTitleEnter);
title2.addEventListener("mouseleave" , handleTitleLeave);
//other way to use event
title2.onmouseover = handleTitleEnter;
//window object event listener
window.addEventListener("resize", handleWindowResize);
window.addEventListener("copy", handleWindowCopy);
window.addEventListener("online", handleWindowOnline);
window.addEventListener("offline", handleWindowOffline);
위의 예시에서 두 가지 방법으로 이벤트를 처리 하고있다
1. addEventListener
-> removeEventListener 로 이벤트 제거가능
2. on[event]
Window Object 에 있는 프로퍼티 를 사용해서 도 html 의 요소들을 js 로 동적으로 바꿀수 있는데, 위에 예시에선
window size 를 바꿀시, "handleWindowResize" 라는 이벤트 핸들러를 call 하게 되고, document Object 의 요소중하나인 body->style->backgroundColor 를 "tomato" 라는 색으로 변경 시키게 해준다.