-
Event
마우스로 해당 영역에 마우스를 올리거나 클릭, copy/paste 했을 때 등 어떤 행동이 발생했을 때 어떤 기능을 수행할지 function으로 정의할 수 있다.
이벤트 사용하기
1. title.addEventListener("이벤트이름", 함수이름);
-> .remmoveEventListener 을 통해 삭제할 수 있다.
const h1 = document.querySelector(".hello:first-child h1"); console.dir(h1); //클릭 시 색 변경 function handleTitleClick(){ console.log("click!"); h1.style.color = "blue"; } //마우스가 해당 영역에 올라오면 출력 function handleMouseEnter() { console.log("mouse is here"); h1.innerText = "Mouse is here!"; } //마우스가 해당 영역을 떠나면 출력 function handleMouseLeave() { h1.innerText = "Mouse is gone!"; }; h1.addEventListener("click",handleTitleClick); h1.addEventListener("mouseenter", handleMouseEnter); h1.addEventListener("mouseleave", handleMouseLeave);
2. title.on함수이름();
const h1 = document.querySelector(".hello:first-child h1"); console.dir(h1); //클릭 시 색 변경 function handleh1Click(){ console.log("click!"); h1.style.color = "blue"; } //마우스가 해당 영역에 올라오면 출력 function handleMouseEnter() { console.log("mouse is here"); h1.innerText = "Mouse is here!"; } //마우스가 해당 영역을 떠나면 출력 function handleMouseLeave() { h1.innerText = "Mouse is gone!"; }; h1.onclick = handleh1Click; h1.onmouseenter = handleMouseEnter; h1.onmouseleave = handleMouseLeave;
* 그 밖의 이벤트들
1. resize
//창 크기를 바꾸면 background 색상 변경 function handleWindowResize() { document.body.style.background = "tomato"; } window.addEventListener("resize", handleWindowResize);
2. copy
//copy 시 alert 팝업 function handleWindowcopy() { alert("copier!"); } window.addEventListener("copy", handleWindowcopy);
※더 많은 event 들은 console.dir(document); 이나 MDN 사이트 참조
Event와 if-else
이벤트가 다수번 일어날 때 조건을 확인하여 원하는 기능이 실행되게 할 수 있다.
1.
const h1 = document.querySelector(".hello:first-child h1"); //클릭할 때마다 색 변경 (blue - tomato) function handleTitlelick(){ if(h1.style.color == "blue") { h1.style.color = "tomato"; } else { h1.style.color = "blue"; } } h1.addEventListener("click", handleTitlelick);
2. 가독성 개선 버전
//클릭할 때마다 색 변경 (blue - tomato) //가독성 개선 버전 function handleTitlelick(){ const currentColor = h1.style.color; let newColor; if(currentColor === "blue") { newColor = "tomato"; } else { newColor = "blue"; } h1.style.color = newColor; } h1.addEventListener("click", handleTitlelick);
3. JS와 CSS 따로 사용하기
-> CSS를 더 이용할 수 있다.
↓CSS
body { background-color: bisque; } h1 { color: cornflowerblue; transition:color .5s ease-in-out; } .active { color: tomato; }
↓JS
const h1 = document.querySelector(".hello:first-child h1"); function handleTitlelick(){ if(h1.className === "active"){ //"active"를 통해 JS와 CSS를 연결 h1.className = ""; } else { h1.className = "active"; } //여기서 h1.className은 getter이면서 동시에 setter이다 console.log("click!"); } h1.addEventListener("click", handleTitlelick);
3번의 "active" 는 사용자가 정의한 것(raw String)이므로 CSS에서 1번, JS에서 2번 등장하는 모든 active 가 정확하게 (오타없이) 작성되어야 정상 작동한다. 만약 수정할 경우 작성된 active를 모두 수정해야하므로 오류 발생 확률이 증가한다. (오타/ 빼먹음)
↓CSS
body { background-color: bisque; } h1 { color: cornflowerblue; transition:color .5s ease-in-out; } .clicked { color: tomato; }
↓JS
const h1 = document.querySelector(".hello:first-child h1"); function handleTitlelick(){ console.log("click!"); const clickedClass = "clicked"; if(h1.className === clickedClass){ h1.className = ""; } else { h1.className = clickdClass; } } h1.addEventListener("click", handleTitlelick);
css에서 active를 clicked라고 바꿀 때 raw String를 여러 번 사용하는 대신 변수를 지정하고 변수에 raw String을 대입한 후 변수를 사용하면 const clickedClass = "clicked"; 부분만 잘 고쳐 넣으면 된다. 만약 clickedClass를 잘못 적었다면 오류메시지가 나타나므로 오류를 잡기에도 적절하다.
'JS' 카테고리의 다른 글
NodeJS : nodemailer을 이용한 이메일 전송 (0) 2022.05.01 21-12-09 제이쿼리 이벤트 (0) 2021.12.09 노마드코더 6일차 (0) 2021.11.15 노마드코더 4일차 (0) 2021.11.09 노마드 코더 3일차 (0) 2021.11.01