이벤트리스너

게코젤리·2022년 9월 3일
0

1) 이벤트리스너?

  • 이벤트 : 웹페이지에서 일어나는 클릭, 스크롤, 키보드입력, 드래그 등의 동작들.
  • 이벤트리스너 : 이벤트가 발생할 경우 해당 이벤트 처리 핸들러를 추가할 수 있는 오브젝트.

2) 사용

  • DOM객체. addEventListener(이벤트명, 실행할 함수명)

  • 예시1)

const title = document.querySelector('.hello');

title.addEventListener('click', function(){
  title.style.color = "blue";
});
  • 예시2)
const title = document.querySelector('.hello');

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

title.addEventListener('click', handleTitleClick);
// handleTitleClick()로 쓰면 클릭하지 않아도 바로 실행
  • 예시3) if/else, let/const를 활용한 eventlinster
const title = document.querySelector('.hello');

function handleTitleClick() {
  const currentColor = title.style.color;
  let newColor;
  if(currentColor === "blue"){
    newColor = "tomato"
  } else {
    newColor = "blue"
  }
  title.style.color = newColor;
}

title.addEventListener('click', handleTitleClick);

0개의 댓글