Krisztián Balla
Krisztián Balla

Reputation: 20371

How to prevent "blur" event on input field?

I have a form with two input fields user and pass. When the user leaves an empty username field it should be refocused (the blur event should be prevented).

var userInput = document.getElementById("user");

userInput.addEventListener("focus", function(ev) {
  console.log("user.focus");
});

userInput.addEventListener("blur", function(ev) {
  console.log("user.blur");
  if (userInput.value == "") {
    console.log("user.refocus");
    userInput.focus();
  }
});

var passInput = document.getElementById("pass");

passInput.addEventListener("focus", function(ev) {
  console.log("pass.focus");
});

passInput.addEventListener("blur", function(ev) {
  console.log("pass.blur");
});
user: <input id="user" /> pass: <input id="pass" />

The code above is working in the following browsers:

But not in these:

Any idea on how this can be solved cross-browser?

Upvotes: 0

Views: 2387

Answers (1)

charlietfl
charlietfl

Reputation: 171669

I'm not going to pretend to explain why this doesn't work in some browsers but using a really short setTimeout() for the refocusing allows it to work in Firefox at least.

My reasoning for trying this approach was to let the original blur event complete before focusing again

var userInput = document.getElementById("user");

userInput.addEventListener("focus", function(ev) {
  console.log("user.focus");
});

userInput.addEventListener("blur", function(ev) {
  console.log("user.blur");
  if (userInput.value == "") {
    console.log("user.refocus");
    setTimeout(()=>{
       userInput.focus();
    },50)
  }
});

var passInput = document.getElementById("pass");

passInput.addEventListener("focus", function(ev) {
  console.log("pass.focus");
});

passInput.addEventListener("blur", function(ev) {
  console.log("pass.blur");
});
user: <input id="user" /> pass: <input id="pass" />

Upvotes: 2

Related Questions