개발노트

5. [Javascript] Events 발생시키기 (with function) 본문

웹 개발/Javascript

5. [Javascript] Events 발생시키기 (with function)

mroh1226 2023. 5. 17. 11:37
반응형

fuction을 호출하기 위해서는 직접 소스에 작성하는 방법도 있지만, Event와 함께 사용하는 것이 일반적일 것입니다.

 

특정 요소에서 마우스 클릭이나 윈도우창에서 스크롤, 창크기 조정, 복사등 Event가 발생되면 들어주는 Listener가 필요합니다.

 

이와 같은 Listener를 추가하는 방법으로 addEventListener() 라는 메소드를 사용할 수 있습니다.

 


index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="StyleSheet" href="styles.css" />
    <title>Momemtum App</title>
  </head>
  <body>
    <div class="main__title">
      <h1>Click Me!</h1>
    </div>
    <script src="app.js"></script>
  </body>
</html>

 

app.js
const title = document.querySelector(".main__title h1");
console.dir(title);

function handleTitle() {
  title.style.color = "blue";
  title.innerText = "OK";
}

function handleTitle2() {
  title.style.color = "red";
  title.innerText = "Are you sure?";
}
function handleTitle3() {
  title.style.color = "black";
  title.innerText = "Click Me!";
}
function handleResize() {
  document.body.style.backgroundColor = "tomato";
}
function handleCopy() {
  alert("don't do that");
}
title.addEventListener("mouseleave", handleTitle3);
title.addEventListener("mouseenter", handleTitle2);
title.onclick = handleTitle;
window.addEventListener("resize", handleResize);
window.addEventListener("copy", handleCopy);
  1. const title = querySelector(".main__title h1"); 으로 요소를 title 변수에 받아옵니다. 
  2. 요소.addEventListener("이벤트명", function명); 으로 요소에 이벤트가 발생했을 때 function이 호출되도록 연결시킵니다.
  3. 요소도 가능하지만 window라는 객체로 웹창에 대한 Event를 설정할 수 있습니다.

title.onclick = handleTitle;

*위와 같이 요소.onclick 으로도 사용가능합니다.


JavaScript에서 사용할 수 있는 일부 흔히 사용되는 이벤트 종류를 알려드리겠습니다. 
(외우지않고 필요할 때, MDN 공식 페이지에서 검색하시는게 좋습니다.)

  • 클릭 이벤트 (click): 요소를 클릭했을 때 발생합니다.
  • 이중 클릭 이벤트 (dblclick): 요소를 빠르게 두 번 클릭했을 때 발생합니다.
  • 마우스 오버 이벤트 (mouseover): 요소 위로 마우스 커서를 이동했을 때 발생합니다.
  • 마우스 아웃 이벤트 (mouseout): 요소에서 마우스 커서가 벗어났을 때 발생합니다.
  • 키보드 다운 이벤트 (keydown): 키보드의 키를 누를 때 발생합니다.
  • 키보드 업 이벤트 (keyup): 키보드의 키를 뗄 때 발생합니다.
  • 폼 제출 이벤트 (submit): 폼을 제출했을 때 발생합니다.
  • 포커스 이벤트 (focus): 요소가 포커스를 받았을 때 발생합니다.
  • 포커스 아웃 이벤트 (blur): 요소가 포커스를 잃었을 때 발생합니다.
  • 로드 이벤트 (load): 웹 페이지 또는 이미지 등이 완전히 로드되었을 때 발생합니다.

 

- Window Event 종류 보기: https://developer.mozilla.org/en-US/docs/Web/API/Window

 

Window - Web APIs | MDN

The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window.

developer.mozilla.org

 


EventListener 로 function이 호출된 모습.

Listener로 Event 발생을 통해 function을 호출된 모습.

 

반응형
Comments