I'm trying to keep focus on an input element with this code:
<input onblur="this.focus()" />
But it doesn't seem to work.
We can use setTimeout() for this. $('#inp'). on('blur',function () { var blurEl = $(this); setTimeout(function() { blurEl. focus() }, 10); });
To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef hook. Then we call focus on the current value of the ref to focus on the input. to call useRef to create a ref and assign it to inputReference . Then we call inputReference.
The :focus selector is used to select the element that has focus. Tip: The :focus selector is allowed on elements that accept keyboard events or other user inputs.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With