Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome: Blur - Alert - Focus sequence causes infinite alert 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" />

The idea around it is to keep the user focused in the input until he/she enters a valid text in 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 alert popup in Chrome but not in IE.

1. How would you solve this problem?

2. Any ideas on why does this happen?

Notes:

  • I already checked this question but that fix doesn't work in this case: Other question
  • Here's an old Chrome bug related to blur and focus (not sure if it could have anything to do with this, although it is marked as solved): Chrome bug
like image 859
Felipe Correa Avatar asked Oct 29 '22 14:10

Felipe Correa


1 Answers

Here is my solution for chrome:

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>

it work for IE too, but this not for Firefox due to focus() is not working correctly.

like image 132
Terry Lao Avatar answered Nov 02 '22 23:11

Terry Lao