목차
event
event란?
이벤트에는 다양한 것이 있다.
- 클릭했을 때
- 마우스를 가져다 댔을 때
- 마우스를 땔 때
- 와이파이 연결을 해제했을 때
- 드래그 했을 때
등등 여러가지 이벤트가 있다.
그 중 가장 이해하기 쉬운 click 이벤트를 살펴보겠다.
<body>
<div class="hello">
<h1>Click me!</h1>
</div>
<script src="app.js"></script>
</body>
const title = document.querySelector(".hello:first-child h1");
function handleTitleClick() {
title.style.color = "blue";
}
title.addEventListener("click", handleTitleClick);
세부 내용
const title = document.querySelector(".hello:first-child h1");
- title이라는 상수를 선언하면서 값을 넣는다.
- document.querySelector() : 문서(지금은 HTML)의 첫 번째 Element를 반환한다. 일치하는 요소가 없으면 null을 반환한다.
function handleTitleClick() {
title.style.color = "blue";
}
- event가 발생했을 때 실행할 function을 정의한다.
title.addEventListener("click", handleTitleClick);
- 위에 선언했던 title이라는 상수에 addEventListener() 를 적용하고 click 이벤트가 발생하면 handleTitleClick 라는 이름의 function 을 실행하도록 JavaScript에게 시킨다.
- 그러면 function의 내부에 작성한 코드가 실행된다.
'프론트엔드 > Javascript' 카테고리의 다른 글
preventDefault (0) | 2023.09.26 |
---|---|
toggle (0) | 2023.09.26 |
조건문 (0) | 2023.09.19 |
return (0) | 2023.09.19 |
array (0) | 2023.09.18 |