To focus on an element using jQuery is really easy, since all it takes is one function – .focus(). There are cases though were it is just a little bit trickier. mybloggingplanet.com
Let’s take the scenario where after entering a field, you need to validate it, and if the validation fails, you need to return focus to the field. You would expect the following code to do the job:
$(elem).blur(function(){ if (do some validation fails) { $(this).focus(); } });
This code, logically, should work, and indeed it does in Internet Explorer, but Firefox stubbornly refuses to set the focus.
The problem is that the event is firing at the wrong time for Firefox, and therefore the focus event is being lost.
The solution for this is to delay the focusing by a small bit, which then yields a solution that works in all browsers
$(elem).blur(function(){ if (do some validation fails) { var $this = $(this); setTimeout(function () { $this.focus(); }, 10); } });
Comments