어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

[js] 이벤트 핸들러 본문

자바스크립트/⚪️ Vanilla

[js] 이벤트 핸들러

비니_ 2025. 1. 12. 17:52
728x90

이벤트 핸들러란?
- HTML 요소에서 발생하는 특정 이벤트(클릭, 로딩, 포커스 등)를 처리
- 여러개 등록 시 마지막으로 지정된 핸들러만 유효

1. 클릭 이벤트 (onclick)
- 클릭시 발생

2. 마우스 오버 이벤트 (onmouseover, onmouseout)
- 요소 위에 마우스를 위치하거나 벗어났을 때 발생하는 이벤트

<div 
    onmouseover="this.style.backgroundColor='yellow'" 
    onmouseout="this.style.backgroundColor='white'" 
    style="width:200px;height:100px;border:1px solid;background:greenyellow;"
  >
  마우스를 올려보세요!</div>
마우스를 올려보세요!

 

3. 폼 제출 이벤트 (onsubmit)
- 폼 양식의 제출 버튼을 클릭 혹은 제출 되었을 때 발생하는 이벤트

<!-- 
  제출 버튼을 누르면 onsubmit이 발생, function onsubmit(){}; 이라고 할 수 있다. 
  onsubmit="return false;"라고 하면 제출이 안됨
-->
<!-- <form onsubmit="if(제출조건만족){return true}return false;" action="location.html"> -->
<form onsubmit="alert('폼 제출'); return false;" action="location.html">
  <input type="text" name="name" placeholder="이름">
  <button type="submit">제출</button>
</form>

 

3. 폼 제출 이벤트 (onsubmit)
- 폼 양식의 제출 버튼을 클릭 혹은 제출 되었을 때 발생하는 이벤트4. 페이지 로드 이벤트 (onload) *많이 사용
- 페이지(DOM)가 로드 되었을 때 발생하는 이벤트

window.onload = function(){
  alert('페이지 완전히 로드')
};


** body 하단에 script를 작성하는 이유: 

-> head에 작성하면 페이지 로딩이 느리면 위에 변수나 태그들을 인식하지 못하여 작성한 script에서 에러가 나타날 수 있다.

5. 키보드 입력 이벤트 (onkeydown, onkeyup, onkeypress)
- 요소 내에서 키보드가 눌렸을 때, 눌린 상태일 때, 떼었을 때 발생하는 이벤트

onkeydown은 다른 언어의 경우 눌렀을 때 한번만 호출
자바스크립트에선 여러번 호출

<input 
  type="text" 
  onkeydown="console.log('onkeydown 눌림')" 
  onkeypress="console.log('onkeypress 눌림')" 
  onkeyup="console.log('onkeyup 눌림')" 
  placeholder="입력해주세요."
>


6. 포커스 이벤트 (onfocus, onblur)
- 요소 내 포커스가 생기거나 벗어났을 때 발생하는 이벤트
- 중복된 아이디 검사 할 때 사용

<input 
  type="text" 
  onfocus="this.style.backgroundColor='lightyellow'"
  onblur="this.style.backgroundColor='green'"
  placeholder="포커스를 맞춰보세요"
>



728x90

'자바스크립트 > ⚪️ Vanilla' 카테고리의 다른 글

이벤트 핸들러  (0) 2025.01.18
[js] 이벤트 리스너  (0) 2025.01.14
[js] HTMLElement 요소 속성  (0) 2025.01.12
[js] with 구문  (0) 2025.01.12
[js] 콘솔 함수, document 메서드  (0) 2025.01.11
Comments