JavaScript에서 요소가 포커스를 잃을 때 이벤트가 발생하는 방법은 무엇인가요?


JavaScript에서 요소가 포커스를 잃을 때 이벤트를 처리하기 위해 blur 이벤트를 사용할 수 있습니다. 이 이벤트는 요소가 포커스를 잃을 때 발생합니다.

<input type="text" id="myInput">

<script>
  const input = document.getElementById("myInput");
  input.addEventListener("blur", function() {
    console.log("Input lost focus");
  });
</script>

위의 예제에서는 blur 이벤트를 사용하여 myInput 요소가 포커스를 잃을 때 "Input lost focus" 메시지가 콘솔에 출력됩니다.

또한, onblur 속성을 사용하여 HTML 요소에 직접 이벤트 핸들러를 추가할 수도 있습니다.

<input type="text" id="myInput" onblur="myFunction()">

<script>
  function myFunction() {
    console.log("Input lost focus");
  }
</script>

위의 예제에서는 onblur 속성을 사용하여 myInput 요소가 포커스를 잃을 때 myFunction 함수가 호출되고 "Input lost focus" 메시지가 콘솔에 출력됩니다.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.