But that does not work. ...">

Maintaining input tag focus

I am trying to focus on an input element with this code:

<input onblur="this.focus()" /> 

But that does not work.

+4
source share
1 answer

If we just call .focus() directly on the blur event, it will restore focus, but there really will not be a text cursor. To handle this, we need to let the element lose focus and then return it in a few milliseconds. For this we can use setTimeout() .

 $('#inp').on('blur',function () { var blurEl = $(this); setTimeout(function() { blurEl.focus() }, 10); }); 

Here is a working example . Be careful - you cannot leave the text field after entering it =)

EDIT I used jQuery, but this can be easily done without it.
EDIT2 Here's a clean version of JS fiddle

 <input type="text" id="elemID" /> <script type="text/javascript"> document.getElementById('elemID').onblur = function (event) { var blurEl = this; setTimeout(function() { blurEl.focus() }, 10); }; </script> 
+9
source

All Articles