Chrome: Blur - Alert - Focus sequence triggers an endless warning loop

Consider this code:

var input = document.getElementById("hello");
input.addEventListener('blur', function() {
  alert('hello');
  input.select();
  input.focus();
});
<input type="text" value="hello" id="hello" />
Run codeHide result

The idea around this is for the user to focus on the input until he / she enters the actual text into it. This is a simplified version of the code.

Js fiddle here: https://jsfiddle.net/wzwft49w/9/

Problem: If you focus on the input and then blur it, you will get an infinite warning popup in Chrome, but not in IE.

1. How would you solve this problem?

2. Any ideas on why this is happening?

Notes:

  • I already checked this question, but this fix does not work in this case: Another question
  • Chrome, ( , - , ): Chrome
+4
1

:

var inputs = document.querySelectorAll("input"), 
    len = inputs.length, 
    i;
    var gflag=false;

    function myalert(m,o) {
        if (gflag) {
            return;
        }

        gflag=true;
        alert(m);
        o.focus();
        setTimeout(function() {gflag=false;},10);
    }
    
function makeBlurHandler() {
    "use strict";
    return function () {
      if (this.value === "") {
          myalert("Cannot be blank!",this);
          this.nextElementSibling.innerHTML = "Cannot be blank!";
      } else {
          this.nextElementSibling.innerHTML = "";
      }
    };
}

for (i = 0; i < len; i++) {
    inputs[i].addEventListener("blur", makeBlurHandler());
}
.errorMessage {
    color: red;
}
<p>
  <label for="userName">User Name:</label>
  <input type="text" id="userName">
  <span class="errorMessage"></span>
</p>
<p>
  <label for="passWord">Password:</label>
  <input type="text" id="passWord">
  <span class="errorMessage"></span> 
</p>
Hide result

IE, Firefox - () .

+1

Source: https://habr.com/ru/post/1666563/


All Articles