focus blur

lee jae hwan·2022년 8월 14일

브라우저

목록 보기
32/39

focus와 blur이벤트는 버블링되지 않는다.

<form id="form">
  <input type="text" name="surname" value="">
  <input type="text" name="name" value="이름">
</form>

<style> .focused { outline: 1px solid red; } </style>

form요소에 focus, blur이벤트를 할당해도 버블링되지 않기때문에 이벤트위임을 사용할 수 없다.

캡쳐링 이벤트위임

form에서 focus핸들러를 할당하고 ev.target으로 처리를 하면 이벤트위임과 같은 효과를 내는 것이다.

그러나 하위요소에도 이벤트핸들러를 할당한다면 이벤트가 또 발생할 것이.

<form id="form">
  <input type="text" name="surname" value="">
  <input type="text" name="name" value="이름">
</form>

<style> .focused { outline: 1px solid red; } </style>

<script>
  // 캡쳐링 단계에서 핸들러가 트리거되도록 합니다(마지막 인수가 true)
  form.addEventListener("focus", () => form.classList.add('focused'), true);
  form.addEventListener("blur", () => form.classList.remove('focused'), true);
</script>

addEventListener의 3번째 인자로 true를 전달하면 캡쳐링이벤트가 발생한다.



focusin, focusout 이벤트사용

focusin, focusout이벤트는 이벤트버블링이 발생한다.

let f = document.forms.namedItem('form:user');

f.addEventListener('focusin',(event)=>{
   event.target.classList.add('focused');
});
f.addEventListener('focusout',(event)=>{
   event.target.classList.remove('focused');
});

현재 포커스된 요소는 document.activeElement를 통해 확인할 수 있습니다.

기본적으로 포커스를 가질 수 있는 요소노드가 있고 그렇지 않은 요소노드가 있다.

기본적으로 포커스를 가질 수 없는 요소노드에 tabIndex=0;으로 설정하면 포커스를 줄 수 있다.

0개의 댓글