Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel an onBlur event in JavaScript?

I want to set up an onBlur event for an input element that validates the value and, if invalid, "cancels" the blur and refocusses the input. However returning false from onBlur does not cancel the onBlur the way it does with onClick. Is there a solution for this (perhaps using jQuery?)

like image 341
JoelFan Avatar asked Nov 15 '10 15:11

JoelFan


2 Answers

I don't know of any reliable cross-browser way to do this. Usually setting a small timeout in the onblur event and calling focus() when the timer fires works.

For example:

document.getElementById('your_input_id').onblur = function() {
  var self = this;
  setTimeout(function() { self.focus(); }, 10);
}
like image 181
casablanca Avatar answered Oct 20 '22 11:10

casablanca


You can call focus() in the handler.
This will sometimes help.

like image 22
SLaks Avatar answered Oct 20 '22 12:10

SLaks