2.이벤트 객체(e)

강재영's avatar
Aug 29, 2024
2.이벤트 객체(e)
notion image
 
  • 이벤트 발생: 예를 들어 사용자가 버튼을 클릭하거나 마우스를 버튼 위로 올렸을 때, 브라우저는 해당 이벤트가 발생했다는 사실을 감지합니다.
  • 이벤트 객체 생성: 이벤트가 발생하면 브라우저는 이벤트와 관련된 다양한 정보를 담은 객체를 생성합니다. 이 객체가 바로 이벤트 객체입니다. 객체의 이름은 e, event, evt 등으로 자유롭게 지정할 수 있습니다.
  • 이벤트 객체 전달: 이벤트 핸들러 함수가 실행될 때, 브라우저는 자동으로 이 이벤트 객체를 첫 번째 인수로 함수에 전달합니다. 이로 인해 함수 내부에서 e를 통해 이벤트와 관련된 정보를 사용할 수 있게 됩니다.
 

2. thise.target 의 차이

이벤트 위임 같은 경우에서는 this는 이벤트 리스너가 등록된 부모 요소를 가리키고, e.target은 실제 이벤트가 발생한 자식 요소를 가리키게 됩니다. 즉 일부상황에서는 같이 동작하는것 처럼보여도 다르다
 
notion image

예시 코드

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Event Delegation Test</title> <style> button { margin: 5px; padding: 10px; font-size: 16px; } #button-container { padding: 20px; border: 2px solid #000; } </style> </head> <body> <div id="button-container"> <button class="color-btn">Button 1</button> <button class="color-btn">Button 2</button> <button class="color-btn">Button 3</button> <button class="color-btn">Button 4</button> </div> <script> const container = document.querySelector("#button-container"); // Event delegation with 'this' container.addEventListener("mouseover", function(e) { console.log("Using 'this':"); console.log(this); // This will refer to the container this.style.backgroundColor = "lightcoral"; // Changes container color, not button }); // Event delegation with 'e.target' container.addEventListener("mouseover", function(e) { console.log("Using 'e.target':"); console.log(e.target); // This will refer to the actual button being hovered if (e.target && e.target.classList.contains('color-btn')) { e.target.style.backgroundColor = "lightgreen"; // Changes the actual button color } }); // Reset color on mouse out container.addEventListener("mouseout", function(e) { if (e.target && e.target.classList.contains('color-btn')) { e.target.style.backgroundColor = ""; // Reset button color } this.style.backgroundColor = ""; // Reset container color }); </script> </body> </html>
 
 
위처럼 이벤트를 바인딩한 요소를 this로 그안의 요소를 e.target으로 잡을 수 있다.
 

3. addEventListener() 메서드

💡
1. click : 요소를 클릭할 때 발생합니다.
2. dblclick : 요소를 더블 클릭할 때 발생합니다.
3. mousedown : 요소에서 마우스 버튼이 눌릴 때 발생합니다.
4. mouseup : 요소에서 마우스 버튼이 떼어질 때 발생합니다.
5. mousemove : 요소에서 마우스가 움직일 때 발생합니다.
. mouseover : 요소에 마우스 커서가 올라갈 때 발생합니다.
7. mouseout : 요소에서 마우스 커서가 벗어날 때 발생합니다.
. keydown : 키보드에서 키를 누를 때 발생합니다.
9. keyup : 키보드에서 키를 뗄 때 발생합니다.
10. submit : 폼을 제출할 때 발생합니다.
11. change : 요소의 값이 변경될 때 발생합니다.
12. load : 웹 페이지나 이미지 등이 로딩되었을 때 발생합니다.
 
  • change의 경우 select의 변화를 탐지할 수 있다.
 
<select id="mySelect"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> <script> mySelect.addEventListener("change", function(e) { console.log("Change event triggered. Selected value:", e.target.value); }); </script>
 
Share article

강재영 블로그