Javascript

[Javascript] focus와 blur

yangjoy 2022. 1. 18. 16:05

focus / blur 이벤트

✔️ focus

  • 사용자가 클릭하거나 tab 키를 눌러 요소로 이동해 해당 요소에 포커스가 되었을 때 발생
  • 이벤트 핸들러에서 주로 focus 되었을 때 에러 메시지를 숨김.

✔️ blur

  • 포커스를 잃을 때 발생
  • 이벤트 핸들러에서 이메일이 잘 입력되었는지 확인하고 잘 입력되지 않은 경우엔 에러를 보여줌.

이메일에 @가 들어가지 않으면 invalid 클래스를 추가해 에러를 알림

focus 되었을때는 에러를 사라지게 만듬.

<body>
    이메일 : <input type="email" id="input">
    <div id="error"></div>
    
    <script>
        let input = document.querySelector('#input');
        let error = document.querySelector('#error');
        
        input.addEventListener('blur', function(){
            if(!input.value.includes('@')){
                input.classList.add('invalid');
                error.innerHTML = "올바른 이메일 주소를 입력해주세요";
                
            } 
        });
        input.addEventListener('focus', function(){
            if(this.classList.contains('invalid')){
                this.classList.remove('invalid');
                error.innerHTML = "";
            }
        })

    </script>
</body>

 

focus, blur 메서드

✔️ elem.focus()와 elem.blur() 메서드를 사용하면 요소에 포커스를 주거나 제거할 수 있다.

✔️ 이벤트 핸들러에서 방문자가 유효하지 않은 것을 입력하면 해당 요소에서 focus를 빠져나가지 못하게 할 수 있다.

<body>
    이메일 : <input type="email" id="input">
    <input type="text" style="width:220px" placeholder="이메일 형식이 아닌 값을 입력하고 여기에 포커스를 주세요">
    
    <script>
        let input = document.querySelector('#input');

        input.onblur = function(){
            if(!this.value.includes('@')){
                this.classList.add("error");
                input.focus();
            } else{
                this.classList.remove("error");
            }
        }
    </script>
</body>