[JavaScript] Events에 대해서

윤현서·2024년 5월 13일

JavaScript

목록 보기
2/7

0. Document Obj

  console.dir(document)    // html document를 가져옴
  document.title_h1           //문서 제목 확인
  document.body            //특정 태그만 가져올 수도 있음
  document.title_h1 = "Hi"    //문서 제목 변경도 가능!

1. HTML 문서 JS로 가져오는 법

  1. id로 가져오기
const title_h1 = document.getElementById("title_h1") 
console.log(title_h1);
console.dir(title_h1); //dir을 열어서 뭘 가져올 수 있는지 확인 가능. 진짜 많음!
  1. class name로 가져오기
const hellos = document.getElementsByClassName("hello");
//array로 한번에 가져오므로 xx.xx 형태로 가져올 수 없음.
console.log(hellos);
  1. tag name으로 가져오기
const title_name = document.getElementsByTagName("h1");
console.log(title_name);
  1. 🍀querySelectorquerySelectorAll🍀
    1. querySelector
      element를 CSS 방식으로 검색 가능(=class 내부에 있는 h1을 검색가능)
      조건에 해당하는 태그들 중 맨 처음 태그만 가져옴!!
      .hello h1:first-child << 이런 selector도 넣을 수 있다는 말
    const titleQS = document.querySelector(".hello h1");
    console.log(titleQS);```
  1. querySelectorAll
    조건에 해당하는 태그들 다 가져옴!!!
const titleQSA = document.querySelectorAll(".hello h1");
console.log(titleQSA);

3. ✨Events✨

events : dir에서 on으로 시작하는 것들, 인식할 모든 동작들

✏️ event 사용법
1. element 찾기
2. event listen 하기
3. event에 반응하기

listen하고 싶은 이벤트 찾는 법
방법 1. 검색
ex : h1 html element mdn에서 Web APIs 가 제목에 있는 사이트 들어가기
mdn 뜻 : Mozilla Developer Network


방법 2. console.dir() 에서 이벤트 찾기

  1. element 찾기
const title_h1 = document.querySelector("div.hello:first-child h1");
console.log(title_h1);
  1. event listen 하기
//작성법 1 (선호)
title_h1.addEventListener("click", handleTitleClick/* 괄호 안 씀. 대신 실행하므로 */);
//작성법 2
// title_h1.onclick = handleTitleClick;
  1. event에 반응하기
function handleTitleClick(){
  //클릭했을 때 색 바꾸기
    const currentColor = title_h1.style.color;
    let newColor;
    if (currentColor === "blue") {
        newColor = "tomato";
    } else {
        newColor = "blue";
    }
    title_h1.style.color = newColor;
}

마우스가 올라가 있을 때/올라가 있지 않을 때 event 인식하기

올라와 있을 때

function handleMouseEnter(){
    console.log("mouse is here");
    title_h1.innerText = "Mouse is here!";
}
title_h1.addEventListener("mouseenter", handleMouseEnter);

올라와 있지 않을 때

function handleMouseLeave(){
    title_h1.innerText = "Mouse is gone!";
}
title_h1.addEventListenr("mouseleave", handleMouseLeave);

기타 이벤트들

  1. 창 크기 조절 이벤트
function handleWindowResize(){/* 창 크기 조절 > 배경색 토마토 */
    document.body.style.backgroundColor = "tomato";
}
window.addEventListener("resize", handleWindowResize);
  1. 복사 이벤트
function handleWindowCopy(){/* 복사 > 알람 */
    alert("copier!");
}
window.addEventListener("copy", handleWindowCopy);
  1. wifi online/offline
function handleWindowOffline(){
    alert("SOS no WIFI");
}
window.addEventListener("offline", handleWindowOffline)
//
function handleWindowOnline(){
    alert("ALL GOOOOD!");
}
window.addEventListener("online", handleWindowOnline);
profile
HUFS CSE 22 / TAB 42

0개의 댓글