📌Language/JavaScript

자바스크립트로 크롬 앱 만들기 - 노마드 코더 클론코딩 #6 HTML element event 찾는 방법 2가지, addEventListener 사용

hellohailie 2022. 4. 8. 13:49

listen하고 싶은 event 찾는 방법!
1. 구글에 찾고 싶은 element의 이름 검색하기 ex) h1 html element mdn(mozilla developer network)
 그 중에서 web APIs 이 포함된 페이지 찾기 (JS 관점의 HTML heading element란 의미)

 

https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement

 

HTMLHeadingElement - Web APIs | MDN

The HTMLHeadingElement interface represents the different heading elements, <h1> through <h6>. It inherits methods and properties from the HTMLElement interface.

developer.mozilla.org

 

 

 

2. console.dir을 통해서 element를 console에 출력시키기 console.dir(title);=> 여기서도 사용가능한 event 찾을 수 있다. property 이름 앞에 on 이 있다면 그게 바로 event listener!!!! 사용할때는 on 빼고 쓰기

 

 

 


const title = document.querySelector(".hello:first-child h1");

console.dir(title);

function handleTitleClick(){
    title.style.color = "blue";
}

function handleMousEenter(){
    title.innerText = "Mouse is here!";
}

function handleMouseLeave(){
    title.innerText = "Mouse is gone.";
}
title.addEventListener("click", handleTitleClick);
title.addEventListener("mouseenter", handleMousEenter);
title.addEventListener("mouseleave", handleMouseLeave);

 

마우스 클릭, 마우스를 글씨 위에 올릴때, 글씨 위에서 마우스 뗄 때 효과가 나타나게 했다. 



참고) style은 CSS를 통해서 변경되어야 한다.

 

 


event listener 사용하기 (addEventListener)

 

title.addEventListener("click", handleTitleClick);
title.onclick = handleTitleClick;
이 두개는 같다. 

 

근데 addEventListener를 더 선호하는 까닭은 removeEventListener를 통해서 event listener를 제거할 수 있기 때문이다. (더 보기가 좋다. )

 

document.body, head, title이 중요해서 존재하는거고, 나머지 element들은 querySelector나 getElementByld 등으로 찾아와야한다.

ex) document.querySelector(“h1”);

 

 

const h1 = document.querySelector(".hello:first-child h1");

console.dir(h1);

function handleTitleClick(){
    h1.style.color = "blue";
}

function handleMousEenter(){
    h1.innerText = "Mouse is here!";
}

function handleMouseLeave(){
    h1.innerText = "Mouse is gone.";
}

function handleWindowResize(){
    document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy(){
    alert("copier!");
}
function handleWindowOffline(){
    alert("no wifi!");
}
function handleWindowOnline(){
    alert("what a relif!");
}

h1.addEventListener("click", handleTitleClick);
h1.addEventListener("mouseenter", handleMousEenter);
h1.addEventListener("mouseleave", handleMouseLeave);

window.addEventListener("resize", handleWindowResize);
window.addEventListener("copy", handleWindowCopy);
window.addEventListener("offline", handleWindowOffline);
window.addEventListener("online", handleWindowOnline);

 

window는 기본제공