Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  166] [ 1]  / answers: 1 / hits: 27316  / 11 Years ago, wed, march 27, 2013, 12:00:00

I'm trying to keep focus on an input element with this code:



<input onblur=this.focus() />


But it doesn't seem to work.


More From » html

 Answers
41

If we just call .focus() right on blur event, it will restore focus, but actually there will be no text cursor. To handle this we have to let element to lose focus and then return it in few milliseconds. We can use setTimeout() for this.



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


Here's working example. Be careful - you can't leave text field after you enter it =)



EDIT I used jQuery, but it can be easily done without it.

EDIT2 Here's pure JS version 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>

[#79288] Wednesday, March 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;