[JS] 클릭 이벤트 실습

Chen·2024년 6월 5일
0

Javascript

목록 보기
6/22
post-thumbnail

[번외] vw, vh

height라고 vh 단위만 써야 하는 게 아님

아래와 같은 경우 vw을 기준으로 4:3 비율의 박스

.stage {
    width: 100vw;
    height: 75vw;
}

[번외] cover, contain

background-image에서 cover는 꽉차게 해서 넘치게 하는 반면, contain은 이미지가 온전히 다 보이도록 한다는 차이점 존재

.ilbuni {
    width: 100px;
    height: 100px;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    background-size: contain;
}

초기 버전

for(let i = 0; i < ilbuniGroup.length; i++){
    ilbuniGroup[i].addEventListener('click', clickHandler);
}

방식 1 (직접 객체 생성)

const stage = document.querySelector('.stage');

function clickHandler(e){
    // console.log(e.currentTarget)
    console.log(this);
    stage.removeChild(this);
}

방식 2 (parentNode로 접근)

// const stage = document.querySelector('.stage');

function clickHandler(e){
    // stage.removeChild(this);
    console.log(this.parentNode);
    this.parentNode.removeChild(this);
}

개선 버전 (feat. 이벤트 위임)

for 문은 메모리를 많이 잡아먹아서 성능이 안 좋아짐 (시간복잡도)
클릭한 객체의 부모에 이벤트 위임을 해서 성능 개선을 해보자

즉, stage에다가 event 한 번 걸어줘서 stage가 이벤트를 처리하게끔

const stage = document.querySelector('.stage');

function clickHandler(e){
    console.log(e.target);
    if(e.target.classList.contains('ilbuni')){
        stage.removeChild(e.target) 
    }
}

stage.addEventListener('click', clickHandler)

이벤트 위임의 장점 (생각보다 단순한 장점.....)

  1. 메모리
  2. 데이터 수십 개 로드할 때 이벤트리스너를 안 걸어줘도 됨(부모와 클릭한 타겟에만 집중)
    ex. 페이스북 좋아요
profile
현실적인 몽상가

0개의 댓글